django rest framework nested relationships - python

I have the following models -
class Jobdtl(models.Model):
jobdtl_id = models.IntegerField(primary_key=True)
jobdtl_cmd = models.TextField(blank=True)
jobdtl_envfile = models.TextField(blank=True)
jobdtl_retnsn = models.SmallIntegerField(blank=True, null=True)
jobdtl_allowadhoc = models.CharField(max_length=1, blank=True)
jobdtl_waitop = models.CharField(max_length=1, blank=True)
class Meta:
managed = False
db_table = 'jobdtl'
class Jobmst(models.Model):
jobmst_id = models.IntegerField(primary_key=True)
jobmst_prntid = models.IntegerField(blank=True, null=True)
jobmst_active = models.CharField(max_length=1, blank=True)
jobmst_evntoffset = models.SmallIntegerField(blank=True, null=True)
jobmst_name = models.TextField(blank=True)
jobmst_owner = models.IntegerField(blank=True, null=True)
jobmst_crttm = models.DateTimeField()
jobdtl_id = models.ForeignKey('Jobdtl', db_column='jobdtl_id', related_name='mstdtl', blank=True, null=True)
jobmst_lstchgtm = models.DateTimeField(blank=True, null=True)
def __unicode__(self):
return self.jobmst_name
class Meta:
managed = False
db_table = 'jobmst'
I'm trying to generate a json similar to what we have here -
http://stackoverflow.com/questions/19709101/django-rest-framework-multiple-models
using the steps here -
http://stackoverflow.com/questions/16793608/how-to-write-a-django-rest-framework-serializer-field-to-merge-data-from-gener
These are my serializers -
class JobmstSerializer(serializers.ModelSerializer):
class Meta:
model = Jobmst
class JobdtlSerializer(serializers.ModelSerializer):
jobmst_id = JobmstSerializer(many=True)
class Meta:
model = Jobdtl
And this is my view
class ResultsList(ListAPIView):
def list(self, request, *args, **kwargs):
jobmstquery = Jobmst.objects.using('Admiral').all()
jobdtlquery = Jobdtl.objects.using('Admiral').all()
results = list()
entries = list(chain(jobmstquery, jobdtlquery)) # combine the two querysets
for entry in entries:
type = entry.__class__.__name__.lower() # 'jobmst', 'jobdtl'
if isinstance(entry, Jobmst):
serializer = JobmstSerializer(entry)
dictionary = {'type': jobmst, 'jobmst_id': jobmst_id, 'jobmst_type': jobmst_type, 'jobmst_prntid': jobmst_prntid, 'jobmst_active': jobmst_active, 'evntmst_id': evntmst_id, 'jobmst_evntoffset': jobmst_evntoffset, 'jobmst_name': jobmst_name, 'jobmst_mode': jobmst_mode, 'jobmst_owner': jobmst_owner, 'jobmst_desc': jobmst_desc, 'jobmst_crttm': jobmst_crttm, 'jobdtl_id': jobdtl_id, 'jobmst_lstchgtm': jobmst_lstchgtm}
if isinstance(entry, Jobdtl):
serializer = JobdtlSerializer(entry)
dictionary = {'type': jobdtl, 'jobdtl_id': jobdtl, 'jobdtl_cmd': jobdtl_cmd, 'jobdtl_envfile': jobdtl_envfile, 'jobdtl_retnsn': jobdtl_retnsn, 'jobdtl_allowadhoc': jobdtl_allowadhoc, 'jobdtl_waitop': jobdtl_waitop}
results.append(dictionary)
return Response(results)
I tie it through my URL -
urlpatterns = patterns('TidalDEV.views',
url(r'^TidalDEV/$', 'ResultsList'),
url(r'^TidalDEV/(?P<pk>[0-9]+)/$', 'ResultsList'),
)
But when I hit my URL at http://localhost/TidalDEV/ or http://localhost/TidalDEV/50244/
I get slammed with an error -
Exception Type: TypeError
Exception Value:
__init__() takes 1 positional argument but 2 were given
Exception Location: D:\Python33\lib\site-packages\django\core\handlers\base.py in get_response, line 114

I ended up doing the following and it worked -
class JobdtlSerializer(serializers.ModelSerializer):
class Meta:
model = Jobdtl
class JobmstSerializer(serializers.ModelSerializer):
jobdtl_id = JobdtlSerializer()
class Meta:
model = Jobmst
then connected with the variation of the default views -
#csrf_exempt
def jobmst_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
DEV = Jobmst.objects.using('AdmiralDEV').all()
serializer = JobmstSerializer(DEV, many=True)
return XMLResponse(serializer.data)
elif request.method == 'POST':
data = XMLParser().parse(request)
serializer = JobmstSerializer(data=data)
if serializer.is_valid():
serializer.save()
return XMLResponse(serializer.data, status=201)
else:
return XMLResponse(serializer.errors, status=400)
#csrf_exempt
def jobmst_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
DEV = Jobmst.objects.using('AdmiralDEV').get(jobmst_id=pk)
except Jobmst.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = JobmstSerializer(DEV)
return XMLResponse(serializer.data)
elif request.method == 'PUT':
data = XMLParser().parse(request)
serializer = JobmstSerializer(DEV, data=data)
if serializer.is_valid():
serializer.save()
return XMLResponse(serializer.data)
else:
return XMLResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
DEV.delete()
return HttpResponse(status=204)
That allowed me to get from the 2 separate models. It's unformatted and ugly but proves it can be done. Need to figure out how to link more than these 2 models now (I have 5 minimum).

Related

drf_yasg #swagger_auto_schema not showing the required parameters for POST Request

I am using django-yasg to create an api documentation. But no parameters are showing in the documentation to create post request. Following are my codes:
After that in swagger api, no parameters are showing for post request to create the event
model.py
class Events(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(EventCategory, on_delete=models.CASCADE)
name = models.CharField(max_length=250, null=True)
posted_at = models.DateTimeField(null=True, auto_now=True)
location = models.CharField(max_length=100, null=True)
banner = models.ImageField(default='avatar.jpg', upload_to='Banner_Images')
start_date = models.DateField(
auto_now=False, auto_now_add=False, blank=True, null=True)
end_date = models.DateField(
auto_now=False, auto_now_add=False, blank=True, null=True)
description = models.TextField(max_length=2000, null=True)
completed = models.BooleanField(default=False)
def __str__(self):
return f'{self.name}'
class Meta:
verbose_name_plural = "Events"
serializers.py
class EventSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True, many=False)
category = EventCategorySerializer(read_only=True, many=False)
class Meta:
model = Events
fields = '__all__'
views.py
#api_view(['POST'])
#permission_classes([IsAuthenticated])
#user_is_organization
#swagger_auto_schema(
request_body=EventSerializer
)
def registerEvent(request):
"""
To Register an events, you must be an organization
"""
data = request.data
print("==================")
print(data)
print("==================")
try:
Event = Events.objects.create(
user = request.user,
category=EventCategory.objects.get(category=data['category']),
name=data['name'],
location=data['location'],
start_date=data['start_date'],
end_date=data['end_date'],
description=data['description'],
completed=data['completed'],
)
serializer = EventSerializer(Event, many=False)
Event = Events.objects.get(id=serializer.data['id'])
Event.banner = request.FILES.get('banner')
Event.save()
serializer = EventSerializer(Event, many=False)
return Response(serializer.data)
except:
message = {'detail': 'Event with this content already exists'}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
I got it running with following changes in views.py
#swagger_auto_schema(
methods=['post'],
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['category','name', 'location', 'start_date', 'end_date', 'description', 'completed', 'banner'],
properties={
'category':openapi.Schema(type=openapi.TYPE_STRING),
'name':openapi.Schema(type=openapi.TYPE_STRING),
'location':openapi.Schema(type=openapi.TYPE_STRING),
'start_date':openapi.Schema(type=openapi.TYPE_STRING, default="yyyy-mm-dd"),
'end_date':openapi.Schema(type=openapi.TYPE_STRING, default='yyyy-mm-dd'),
'description':openapi.Schema(type=openapi.TYPE_STRING),
'completed':openapi.Schema(type=openapi.TYPE_BOOLEAN, default=False),
'banner': openapi.Schema(type=openapi.TYPE_FILE),
},
),
operation_description='Create an events'
)
#api_view(['POST'])
#permission_classes([IsAuthenticated])
#user_is_organization
def registerEvent(request):
"""
To Register an events, you must be an organization
"""
data = request.data
print("==================")
print(data)
print(type(data))
category=EventCategory.objects.get(category=data['category']),
print(category)
print(type(data["start_date"]))
print("==================")
try:
Event = Events.objects.create(
user = request.user,
category=EventCategory.objects.get(category=data['category']),
name=data['name'],
location=data['location'],
start_date=data['start_date'],
end_date=data['end_date'],
description=data['description'],
completed=data['completed'],
)
print("****************************")
serializer = EventSerializer(Event, many=False)
Event = Events.objects.get(id=serializer.data['id'])
Event.banner = request.FILES.get('banner')
Event.save()
serializer = EventSerializer(Event, many=False)
return Response(serializer.data)
except ValidationError as e:
return Response({"ValidationError" : e}, status = status.HTTP_400_BAD_REQUEST)
except Exception as e:
message = {'error': e}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
can you modify your swagger_auto_schema decorator like this?
#swagger_auto_schema(
methods=['post',],
request_body=EventSerializer )
All you need to do is place the #swagger_auto_schema on the top. To help it display the parameters create a serializer for it. This way, you only have to change the serializer in the future keeping everything in one place.
API view
#swagger_auto_schema(request_body=serializers.RequestSerializer, method='post')
#api_view(http_method_names=['POST'])
def special_get(request):
data = JSONParser().parse(request)
unique_id = data.get("unique_id", "")
...
Serializer.py
class RequestSerializer(serializers.Serializer):
unique_id = serializers.CharField(max_length=50, allow_null=False, allow_blank=True)
sentence_list = serializers.ListField(
child=serializers.CharField(allow_blank=False, trim_whitespace=True)
)

Django import-export with FK constraint

I have been attempting to import data into my Django project using Django import-export. I have two models Ap and Job, Job has a FK relationship with Ap. Using the Admin, I can select the file and the type, CSV. So far my program seems to run, but gets hung up on the FK. I'm close, something is off and causing the import script to fail.
Models.py
class Ap(models.Model):
line_num = models.IntegerField()
vh = models.IntegerField()
vz = models.IntegerField()
status = models.CharField(
choices=statuses, default="select", max_length=40)
classified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Job(models.Model):
aplink = models.ForeignKey(Ap, related_name=(
"job2ap"), on_delete=models.CASCADE)
job_num = models.IntegerField()
description = models.CharField(max_length=200)
category = models.CharField(
choices=categories, default="select", max_length=40)
status = models.CharField(
choices=statuses, default="select", max_length=40)
dcma = models.BooleanField(default=False),
due_date = models.DateField(blank=True),
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
class ImportView(View):
def get(self, request):
form = ImportForm()
return render(request, 'importdata.html', {'form': form})
def post(self, request):
form = ImportForm(request.POST, request.FILES)
job_resource = JobResource()
data_set = Dataset()
if form.is_valid():
file = request.FILES['import_file']
imported_data = data_set.load(file.read())
result = job_resource.import_data(
data_set, dry_run=True) # Test the data import
if not result.has_errors():
job_resource.import_data(
data_set, dry_run=False) # Actually import now
else:
form = ImportForm()
return render(request, 'importdata.html', {'form': form})
resource.py
class CharRequiredWidget(widgets.CharWidget):
def clean(self, value, row=None, *args, **kwargs):
val = super().clean(value)
if val:
return val
else:
raise ValueError('this field is required')
class ForeignkeyRequiredWidget(widgets.ForeignKeyWidget):
def clean(self, value, row=None, *args, **kwargs):
if value:
print(self.field, value)
return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: value})
else:
raise ValueError(self.field + " required")
class JobResource(resources.ModelResource):
aplink = fields.Field(column_name='aplink', attribute='aplink', widget=ForeignkeyRequiredWidget(Ap,'id'),
saves_null_values=False)
job_num = fields.Field(saves_null_values=False, column_name='job_num', attribute='job_num',
widget=widgets.IntegerWidget())
description = fields.Field(column_name='description', attribute='description', saves_null_values=False,
widget=CharRequiredWidget())
class Meta:
model = Job
fields = ('aplink', 'job_num', 'description',)
clean_model_instances=True
admin.py
class JobResource(resources.ModelResource):
class Meta:
model=Job
fields=('aplink','job_num','description',)
class JobAdmin(ImportExportModelAdmin):
resource_class = JobResource
admin.site.register(Job, JobAdmin)
CSV file, data to import. I have tried leaving the first column empty, as will as putting the Id of the only Ap stored in the table ie 1. I have also tried hard coding the line_num, which is 1200 the first column as well.
CSV file for importing data:
Date importing errors:
In your resources, while defining fields, you need to include id field in the list. So change JobResource to the following:
class JobResource(resources.ModelResource):
class Meta:
model = Job
fields = ('id', 'aplink', 'job_num', 'description')
If you have defined a custom id field, then you will need to provide:
import_id_fields = ('your_id_field')

Unable to POST the data using rest Django - NOT NULL constraint failed: author_id

I have the following error, and I guess the problem with how can I add the author id to the post automatically.
And also I tried to add null=True
author = models.ForeignKey(User, null=True, blank=True)
The error disappeared, but unfortunately, the author's id is still null.
IntegrityError at /auctions/api/addAuction/
NOT NULL constraint failed: auctions_auction.author_id
Request Method: POST
Request URL: http://127.0.0.1:8000/auctions/api/addAuction/
Django Version: 3.1.5
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: auctions_auction.author_id
/auctions/api/serializers.py
class AddAuctionsSerializer(serializers.ModelSerializer):
print("AddA uctionsSerializer Function call")
class Meta:
model = Auction
# Get the current user from request context
def validate_author(self, value):
return self.context['request'].user
author_id = serializers.Field(source='author.id')
fields = ["title", "desc", "image","location","min_value","date_added","author_id"]
read_only_fields = ('author','id','author_id','author.id')
/auctions/api/view.py
class addAuction(APIView):
#permission_classes = [permissions.IsAuthenticated]
#authentication_classes = [SessionAuthentication, BasicAuthentication]
def pre_save(self, obj):
obj.owner = self.request.user
def post(self, request, format=None):
auction = Auction()
auction.author = request.user
serializer = AddAuctionsSerializer(data=request.data)
print(serializer)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
/auctions/api/url.py
path('addAuction/', addAuction.as_view()),
/auctions/model.py
class Auction(models.Model):
location = LocationField()
author = models.ForeignKey(User, on_delete=models.CASCADE,null=False)
# author = models.ForeignKey(User, null=True, blank=True)
title = models.CharField(max_length=300)
desc = models.CharField(max_length=2000, blank=True)
image = models.ImageField(upload_to='auction_images/', blank=True, default = 'auction_images/default/default.svg')
min_value = models.IntegerField()
#date_added = models.DateTimeField()
date_added = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
winner = models.ForeignKey(User, on_delete=models.SET("(deleted)"),
blank=True,
null=True,
related_name="auction_winner",
related_query_name="auction_winner")
final_value = models.IntegerField(blank=True, null=True)
def resolve(self):
if self.is_active:
# If expired
if self.has_expired():
# Define winner
highest_bid = Bid.objects.filter(auction=self).order_by('-amount').order_by('date').first()
if highest_bid:
self.winner = highest_bid.bidder
self.final_value = highest_bid.amount
self.is_active = False
self.save()
# Helper function that determines if the auction has expired
def has_expired(self):
now = datetime.now(timezone.utc)
expiration = self.date_added + timedelta(minutes=AUCTION_DURATION)
if now > expiration:
return True
else:
return False
# Returns the ceiling of remaining_time in minutes
#property
def remaining_minutes(self):
if self.is_active:
now = datetime.now(timezone.utc)
expiration = self.date_added + timedelta(minutes=AUCTION_DURATION)
minutes_remaining = ceil((expiration - now).total_seconds() / 60)
return(minutes_remaining)
else:
return(0)
Try using SlugRelatedField instead of Field.
Like so:
class AddAuctionsSerializer(serializers.ModelSerializer):
# instead of this:
# author_id = serializers.Field(source='author.id')
# do this:
author = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='id', write_only=True)
class Meta:
model = Auction
fields = ["title", "desc", "image","location","min_value","date_added","author"]
# don't put 'author_id' in read_only, because creating is "writing"
# also note that 'author.id' is invalid field
# read_only_fields = ('author','id','author_id','author.id')
read_only_fields = ('id')
# Get the current user from request context
def validate_author(self, value):
return self.context['request'].user
I had the same problem.
You can solve it by overwriting the create method of AddAuctionsSerializer and manually defining instance.author, or by passing the parameter author = request.user, to the save method of AddAuctionsSerializer,

Django Product Total

I'm trying to learn in Django. I'm trying to prepare the inventory application. But I do not calculate the input and output products.
I prepare models & views.
Models:
class Kategori(models.Model):
adi = models.CharField(max_length=10, verbose_name="Kategori")
def __str__(self):
return self.adi
class Birim(models.Model):
birim = models.CharField(max_length=2, verbose_name="Birim")
def __str__(self):
return self.birim
class Urunler(models.Model):
adi = models.CharField(max_length=50, verbose_name="Ürün Adı")
kod = models.PositiveSmallIntegerField(verbose_name="Ürün Kodu", blank=True, null=True)
etkenMadde = models.CharField(max_length=100, verbose_name="İçerik Etken Madde", blank=True, null=True)
tarih = models.DateField(default=datetime.now(), editable=False)
birim = models.ForeignKey(Birim, verbose_name="Birim")
kategori = models.ForeignKey(Kategori, verbose_name="Kategori")
aciklama = models.CharField(max_length=50, verbose_name="Açıklama", blank=True, null=True)
def __str__(self):
return self.adi
class StokCikis(models.Model):
urun = models.ForeignKey(Urunler, related_name="scikis_urun", verbose_name="Ürün")
tarih = models.DateTimeField(default=datetime.now())
miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0)
teslimAlan = models.CharField(max_length=20, verbose_name="Teslim Alan")
tesimEden = models.CharField(max_length=20, verbose_name="Teslim Eden")
def __str__(self):
return self.urun.adi
class StokGiris(models.Model):
urun = models.ForeignKey(Urunler, related_name="sgiris_urun", verbose_name="Ürün")
tedarikci = models.CharField(max_length=100, verbose_name="Tedarikçi", blank=True, null=True)
irsaliyeNo = models.PositiveSmallIntegerField(verbose_name="İrsaliye No", blank=True, null=True)
tarih = models.DateField(default=datetime.now().strftime("%d.%m.%Y"))
miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0)
aciklama = models.CharField(max_length=100, verbose_name="Açıklama", blank=True, null=True)
def __str__(self):
return self.urun.adi
Views.py
def kategori(request):
kategori = Kategori.objects.all()
return render_to_response('stok_kategoriler.html', locals())
def kategoriEkle(request):
kategoriId = request.GET.get('id')
if kategoriId:
ktgr = Kategori.objects.get(pk=kategoriId)
form = KategoriForm(instance=ktgr)
else:
form = KategoriForm
if request.method == 'POST':
if kategoriId:
form = KategoriForm(request.POST, instance=ktgr)
else:
form = KategoriForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/kategoriler')
button = "Ekle"
baslik = "Kategoriler"
return render(request, 'stok_kategori_ekle.html', locals())
def kategoriSil(request):
kategoriId = request.GET.get('id')
kategori = Kategori.objects.get(pk=kategoriId)
kategori.delete()
return HttpResponseRedirect('/stok/kategoriler')
def stokBirimler(request):
birimler = Birim.objects.all()
return render_to_response('stok_birimler.html',locals())
def stokBirimEkle(request):
birimId = request.GET.get('id')
if birimId:
stok_birim = Birim.objects.get(pk=birimId)
form = BirimForm(instance=stok_birim)
else:
form = BirimForm()
if request.method == 'POST':
if birimId:
form = BirimForm(request.POST, instance=stok_birim)
else:
form = BirimForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/birimler/')
baslik = "Stok Birimleri"
return render(request, 'stok_birim_ekle.html', locals())
def stokBirimSil(request):
birimId = request.GET.get('id')
birim = Birim.objects.get(pk=birimId)
birim.delete()
return HttpResponseRedirect('/stok/birimler/')
def stokUrunler(request):
urunler = Urunler.objects.all()
return render_to_response('stok_urunler.html', locals())
def urunEkle(request):
urunId = request.GET.get('id')
if urunId:
stok_urun = Urunler.objects.get(pk=urunId)
form = UrunForm(instance=stok_urun)
else:
form = UrunForm()
if request.method == 'POST':
if urunId:
form = UrunForm(request.POST, instance=stok_urun)
else:
form = UrunForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/urunler/')
baslik = "Stok Ürünleri"
return render(request, 'stok_urun_ekle.html', locals())
def urunSil(request):
urunId = request.GET.get('id')
urun = Urunler.objects.get(pk=urunId)
urun.delete()
return HttpResponseRedirect('/stok/urunler/')
Located in the model StokGiris.miktari and Stok.Cikis.miktari fields need calculation. Total = StokGiris.miktari - StokCikis.miktari and I want to list the records.
If I understand your question correctly, you want to aggregate the values of miktar of both models and subtract them from each other. You can do it with Django built-in aggregation:
from django.db.models import Sum
total = StokGiris.objects.all().aggregate(Sum('miktar')) - StokCikis.objects.all().aggregate(Sum('miktar'))
As for listing the records... Not really sure what you mean again, but some ways to "list the records":
# Just a list of DB items
list_of_stokgiris = list(StokGiris.objects.all())
# Serialized list of dictionaries with the DB values
list_of_stokcikis = StokCikis.objects.values() # You can add an argument to specify which fields you want to be serialized
# Serialized list of tuples with DB values
# I.e. [('Filipp',), ('Artjom',), ('Marat',)]
list_of_urunler = Urunler.objects.values_list('adi') # Same here for the argument. Multiple args are also supported.

django python slug variable in models.py

While I hit the search button..it shows the
Page not found (404)
No Category matches the given query.
My views
def search_in_category(request, slug):
# reset the search params, if present
try:
del request.session['search']
except KeyError:
pass
return search_results(request, slug)
def search_results(request, slug):
category = get_object_or_404(Category, slug=slug)
fields = list(category.field_set.all())
fields += list(Field.objects.filter(category=None))
fieldsLeft = [field.name for field in fields]
if request.method == "POST" or 'search' in request.session:
ads = category.ad_set.filter(active=True,
expires_on__gt=datetime.datetime.now())
# A request dictionary with keys defined for all
# fields in the category.
post = {}
if 'search' in request.session:
post.update(request.session['search'])
else:
post.update(request.POST)
sforms = prepare_sforms(fields, fieldsLeft, post)
isValid = True
for f in sforms:
# TODO: this assumes the form is not required
# (it's a search form after all)
if not f.is_valid() and not f.is_empty():
isValid = False
if isValid:
if request.method == 'POST':
request.session['search'] = {}
request.session['search'].update(request.POST)
return redirect('classifieds_browse_search_results', slug=slug)
for f in sforms:
ads = f.filter(ads)
if ads.count() == 0:
return render_to_response('classifieds/list.html',
{'no_results': True,
'category': category},
context_instance=RequestContext(request))
else:
context = context_sortable(request, ads)
context['category'] = category
return render_to_response('classifieds/list.html', context,
context_instance=RequestContext(request))
else:
sforms = prepare_sforms(fields, fieldsLeft)
return render_to_response('classifieds/search.html',
{'forms': sforms, 'category': category},
context_instance=RequestContext(request))
My models.py
class Category(models.Model):
site = models.ForeignKey(Site)
template_prefix = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=200)
slug = models.SlugField()
enable_contact_form_upload = models.BooleanField(default=False)
contact_form_upload_max_size = models.IntegerField(default=2 ** 20)
contact_form_upload_file_extensions = models.CharField(max_length=200,
default="txt,doc,odf,pdf")
images_max_count = models.IntegerField(default=0)
images_max_width = models.IntegerField(help_text=_(u'Maximum width in pixels.'),
default=1024)
images_max_height = models.IntegerField(help_text=_(u'Maximum height in pixels.'),
default=1024)
images_max_size = models.IntegerField(help_text=_(u'Maximum size in bytes.'),
default=2 ** 20)
images_allowed_formats = models.ManyToManyField(ImageFormat, blank=True)
description = models.TextField(default='')
sortby_fields = models.CharField(max_length=200,
help_text=_(u'A comma separated list of field names that should show up as sorting options.'),
blank=True)
sort_order = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.name + u' Category'
class Meta:
verbose_name_plural = u'categories'
My url
url(r'^search/(?P<slug>[-\w]+)/$', 'browse.search_in_category',
name='classifieds_browse_category_search'),
url(r'^search/results/(?P<slug>[-\w]+)/$', 'browse.search_results',
name='classifieds_browse_search_results'),
This my code, Why I am getting the 404 error? What I have to do for fix this error?
you cannot do
return search_results(request, slug)
do rather this redirect
return redirect(reverse('classifieds_browse_search_results', kwargs={'slug':slug}))
dont forget to import
from django.core.urlresolvers import reverse
from django.shortcuts import redirect

Categories

Resources