Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow maximum number of choices of m2m field in viewset
I want to allow users pick maximum 2 genres. I tried add in models.py, but there was an error. Now, I am thinking of adding code to check the number of picked genres in views.py, or may be in Serializer if it's possible. class Story(models.Model): genre = models.ManyToManyField(Genre) class StorySerializer(serializers.ModelSerializer): genre = GenreSerializer(read_only=True, many=True) ... class StoryView(viewsets.ModelViewSet): queryset = Story.objects.all() serializer_class = StorySerializer def perform_create(self, serializer): serializer.save(author=self.request.user) -
Posting GeoJSON with DRF causes "function st_geomfromewkb(bytea) does not exist"
I set up a Django Rest Framework (DRF) API using django-rest-framework-gis. It works fine to post data from the API's interface, as long as I keep the geometry field to null. But as soon as I try including a GeoJSON in the geometry field (as below)... { "gmlid": "this is a test from DRF interface", "name": "", "envelope": { "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }, "creation_date": null, "xml_source": "" } ...I get the following error: ProgrammingError at /en/api/cityobject/ function st_geomfromewkb(bytea) does not exist LINE 1: ...atest_from_browser', '', '', '', '', ST_Transform(ST_GeomFro... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Request Method: POST Request URL: http://127.0.0.1:8000/en/api/cityobject/ Django Version: 2.2 Exception Type: ProgrammingError Exception Value: function st_geomfromewkb(bytea) does not exist LINE 1: ...atest_from_browser', '', '', '', '', ST_Transform(ST_GeomFro... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Exception Location: /home/me/dj-workspace/my-venv/lib/python3.6/site-packages/django/db/backends/utils.py in _execute, line 84 Python Executable: /home/me/dj-workspace/my-venv/bin/python Python Version: 3.6.8 Python Path: ['/home/me/dj-workspace/myapp', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/me/dj-workspace/my-venv/lib/python3.6/site-packages'] Server time: Sat, 5 Oct 2019 07:49:35 +0000 What may be causing this error? My code looks like this: models.py class Cityobject(models.Model): … -
In Django Admin drop-down list action, is there any function to go to page of other app in the same project when i cilick on GO button
`python def create_estimator_observation(ModelAdmin, request, queryset): url = reverse('admin:estimator_estimator_change', args=[new_estimator.id]) try: link = '%s' % (url, new_estimator.id) except AttributeError: link = 'No Such Estimator' import ipdb; ipdb.set_trace() return format_html(url) ` This code is used to create the create estimator action, and at the stage, i want to go to the change estimator page when i click go. When i click 'go', page url='127.0.0.1:8000/admin/observation/observation/' I'd like to show the page, page url='127.0.0.1:8000/admin/estimator/estimator/f55556bf-1f1b-448b-bf4e-4f6a237f7d58/change/' -
I'm getting 'TypeError' in whenever I edit any entry through forms in Django
Every time I try to edit any entry through a form, it gives Type Error. I have only one model that is BlogPost models.py from django.db import models # Create your models here. class BlogPost(models.Model): """ A title and text for a blog entry""" title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """ return a string representation of the model.""" return self.title This is views file views.py from django.shortcuts import render, redirect from .models import BlogPost from .forms import BlogPostForm def edit_post(request, blog_id): """ edit an entry""" title = BlogPost.objects.get(id=blog_id) post = title.text if request.method != 'POST': form = BlogPostForm(instance=entry) else: form = BlogPostForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('blogs:index', blog_id=title.id) context = {'title': title, 'post': post, 'form': form} return render(request, 'blogs/edit_post.html', context) This is edit post file edit_post.html {extends 'blogs/base.html'} {% block content %} <p>Edit Form:</p> <p>{{ title }}:</p> <form action="{% url 'blogs:edit_post' title.id %}" method="POST"> {% csrf_token %} {{ form.as_p }} <button name="submit">Save changes</button> </form> {% endblock content %} base.html <p> <a href="{% url 'blogs:index' %}">Home</a> - <a href="{% url 'blogs:new_post' %}">Add Post</a> </p> <br> {% block content %}{% endblock content %} This is index/home page file index.html {% extends 'blogs/base.html' %} {% block content … -
i'm having trouble with my django code while i deleting the data from the table form on click of the delete button
But it will showing an error which is (TypeError at /deletecase deletecase() missing 1 required positional argument: 'pk') please help me out this Here is the url link of the page: ```path("deletecase",views.deletecase,name="deletecase")``` THE VIEW FILE FUNCTION: ``` def policcasesdetails(request): cases=Case.objects.all() return render(request,'policeside/policcasesdetails.html',{'cases':cases}) def deletecase(request,pk): obj=Case.objects.get(id=pk) obj.delete() return HttpResponse("Data is Deleted") ``` AND THE FORM IS:- <div class="container"> <div class="content-middle"> <div class="col-md-12 sed-in"> <h3>Cases Details</h3> {% for i in cases %} <div class="col-md-4 sed-top"> <div class="top-sed"> <!-- <img src="{{ i.image.url }}" class="img-responsive" alt=""> --> <!-- <label><span>{{ i.oname }}</span></label> --> </div> <h4> Case Number- <a>{{i.casenumber}}</a> </h4> <p>Case Name- <a href="#">{{i.casename}}</a></p> <p>Case Result- <a href="">{{ i.caseresult }}</a></p> <p>Case Conclusion- <a href="">{{ i.casecoclusion }}</a></p> <p><a href="{% url 'deletecase' i.id %}"> <button type="submit" value="delete" class="btn btn- danger">Delete</button> </p> </div> {% endfor %} <div class="clearfix"> </div> </div> <div class="clearfix"> </div> </div> </div> -
Unable to download a pdf file in a django app?
I've made a django app and there is a file I want user would be able to download on clicking a button. But I'm unabale to download it even though everything seems to be correct. Here's a section my index.html <h3>Download your file here-</h3> <button>Download <a href="/my_website/my_webapp/static/my_webapp/pictures/bill/bill.pdf" download='bill'></a> </button> On clicking the button the file doesn't get downloaded. Can anyone help? -
Applying union() on same model is not recognising ordering using GenericRelation
I have an Article model like this from django.contrib.contenttypes.fields import GenericRelation from django.db import models from hitcount.models import HitCountMixin, HitCount class Article(models.Model): title = models.CharField(max_length=250) hit_count_generic = GenericRelation( HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') when I do Article.objects.order_by('hit_count_generic__hits'), I am getting results.but when I do articles_by_id = Article.objects.filter(id__in=ids).annotate(qs_order=models.Value(0, models.IntegerField())) articles_by_name = Article.objects.filter(title__icontains='sports').annotate(qs_order=models.Value(1, models.IntegerField())) articles = articles_by_id.union(articles_by_name).order_by('qs_order', 'hit_count_generic__hits') getting error ORDER BY term does not match any column in the result set How can i achieve union like this? I had to use union instead of AND and OR because i need to preserve order. ie; articles_by_id should come first and articles_by_name should come second. -
permission denied error while running collectstatic command
I'm deploying my django project on digitalocean.While it runs correctly in my development machine but on running on server, it's not showing static files. not showing static files my settings for static files is, STATIC_URL = '/static/' STATIC_ROOT='/home/gagan_sapora/myprojectdir/saporawebapp/static/' for troubleshooting, i run collectstatic command but it's showing permission denied error. -
How to add urls of two apps in urls.py single project in django?
enter image description here Project1 contains app1 amd app1.. but i dont understand how to put urls of both apps App1 views ----------->>urls at project1 level App2 views------------->>urls at project1 level -
how to filter with multiple values from checkboxes in Django?
I have this Patient model with fields: company, sex, is_alive... In the patient search page, I have checkboxes for these fields. So if users want to search all male alive patient in a company ... they will tick on the checkbox. Then in the backend, in views.py, I collect values of checkboxes and put into a list called "value_list". Next, I do the query search like this: patient_list = Patient.objects.all() if "abc" in value_list: company = Company.objects.get(name="abc") patient_list = patient_list.filter(Q(company=company)) if "alive" in value_list: company = Company.objects.get(name="alive") patient_list = patient_list.filter(Q(company=company)) if "male" in value_list: company = Company.objects.get(name="male") patient_list = patient_list.filter(Q(company=company)) My question is if this way of filtering is efficient and good practice. Please advise. Thank you. -
How to assign objects to groups in django
I need to be able to create a Memo and specify which group(s) can view this specific Memo. One thing I want to avoid doing is using GenericForeignKeys as I have read a lot about how they are costly during database look-ups, etc. I also need to set notifications for this Memo so that a user can mark as read, unread, etc. The notifications will be handled by Django-notifications so that is not and issue unless the answer to the next question can knock out both of these tasks in one swipe.. My question is: how do I create a Memo model with a CharField of group choices and use the user selected choice to assign which group can view this Memo? Somewhat linking objects to groups. I see this post and it seems that it may do what I want but the questions would then be: I am assuming Group in groups = models.ForeignKey(Group, on_delete=models.CASCADE) is the standard Group model in Django being referenced here. How do I add the ability for the user to select which group the Memo applies to? -
How to erase previously set one-time default value
In my django app, I had to set a one-time default value for one of the fields when I tried to migrate. When I did this, however, I accidentally set a wrong value. Ever since then, the same error pops up when I try to migrate: ValueError: invalid literal for int() with base 10: '123e4567-e89b-12d3-a456-426655440000' This is despite the fact that I rectified the issue in my code - it seems like this issue is stuck forever. Anything I can do to fix this? -
Invalid URL '': No schema supplied. Perhaps you meant http://? - Django
I'm a beginner in Django. I'm making a data scraping project, I've made this code but facing problem to download the CSV file. I used The function 'Download' in the file but not getting the desired result. Instead, I'm getting this error Invalid URL '': No schema supplied. Perhaps you meant http://? Here is my code views.py def index(request): if request.method == "POST": url = request.POST.get('url', '') down = request.POST.get('download','') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) p_image = soup.findAll('img', {'class':'s-image','src':re.compile('.jpg')}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price,image in zip(p_name,p_price,p_image): writer = csv.writer(response) row = writer.writerow([name.text, price.text,image['src']]) name_data = [data.text for data in p_name] price_data = [data.text for data in p_price] image_data = [data['src'] for data in p_image] dec = {'name':name_data, 'price':price_data, 'image':image_data} if down: return response else: dec = {} return render(request, 'index.html',dec) When i remove this "if down:" it downloads my csv file correctly, when i keep the if condition it throws error : Invalid URL '': No schema supplied. Perhaps you meant http://? index.html <div class="container"> <div class="row justify-content-md-center"> <div class="col-md-4"> <form method="POST" action="">{% csrf_token %} <h1 class="mb-3 display-4">Amazone Scraper</h1> <input type="text" id="url" name="url" class="form-control" placeholder="URL" required … -
How To Get The Local TIme In Models.DateTimeField() In Django?
I was trying to get the local time in the models section of my models.py file in Django. But this function returns the server time which is about 5 hours less than my local time, so, how do I get this correct? date = models.DateTimeField(default=timezone.now) Thanks In Advance! -
How can i update another model fields when i save another form
Hi i have 2 models Game and Match models.py class Game(models.Model): title = models.CharField(max_length=255) team1score = models.IntegerField(null=True, blank=True,default=0) ... team2score = models.IntegerField(null=True, blank=True,default=0) ... class Match(models.Model): title = models.CharField(max_length=255) game=models.ForeignKey(Game,on_delete=models.CASCADE) team1score = models.IntegerField(null=True, blank=True,default=0) ... team2score = models.IntegerField(null=True, blank=True,default=0) ... forms.py class MatchForm(forms.ModelForm): team1score = forms.IntegerField(widget=forms.TextInput,required=False) team2score = forms.IntegerField(widget=forms.TextInput,required=False) class Meta: model=Match fields=['team1score', 'team2score', ... ] I'm creating a match object with the code below. views.py def creatematch(request,...): form = MatchForm(request.POST or None) if form.is_valid(): match = form.save(commit=False) ... match.save() ... Now, my question is how can i update game.team1score and game.team2score when i create match objects -
Give object same field value as a field of its Foreign Key
I am trying to create a job board website. The user enters a zip code and jobs in a specified radius should be returned. Here is my models.py: class Business(models.Model): name = models.CharField(max_length = 150) address = models.CharField(max_length = 150) city = models.CharField(max_length = 150) zip_code = models.CharField(max_length = 10) state = models.CharField(max_length = 30) phone_number = models.CharField(max_length = 10) def __str__(self): return self.name +", " + self.address + ", " + self.state class Job(models.Model): business = models.ForeignKey(Business, on_delete = "models.CASCADE") title = models.CharField(max_length = 100) description = models.CharField(max_length = 500) zip_code = business.zip_code def __str__(self): return self.title + " - " + self.business.name Upon attempting to filter Job objects by zip code: jobs_in_zip = Job.objects.all().filter(zip_code = zip_code) I realized the Job model did not have a zip_code field. I tried updating the model as such: class Job(models.Model): business = models.ForeignKey(Business, on_delete = "models.CASCADE") zip_code = business.zip_code but this returned AttributeError: 'ForeignKey' object has no attribute 'zip_code' How should I go about this? Thanks in advance. PS: If you have a better title in my mind feel free to change it, I don't think I clearly defined the problem that well. -
Gallery in Django
I have a "Category" model. I want to have it so every time I create a category it creates a directory in my media folder. From there I want to be able to upload images to the relevant folders and have a gallery in my category view that loops through every image in said categories directory. category.html <div class="container"> <div class="row"> {% for image in images %} <div class="col-md-4"> <a href="/media/{{ image }}"> <img src="/media/{{ image }}" class="img-responsive img-thumbnail" width="304" height="236"/> </a> </div> {% endfor %} </div> </div> views.py def category_view(request): images = os.listdir(settings.MEDIA_ROOT) context = { "images": images, } return render(request, "main/category.html", context) This code seems to work but only for the MEDIA_ROOT. I want to loop through a specific category. -
Django: Does not raise error if CharField and TextField are not provided when blank=True
class Test(models.Model): name = models.CharField(blank=True) Now i try to save Test without supplying name Test.objects.create(pk=1) Now i am expecting it should raise an exception saying that name is required. Whereas for other fields it will raise an exception that we have to provide the value So is it some default behaviour for CharField and TextField that blank=True will allow to store empty string -
Auto-increment conflicting slugs on save
I need blog post slugs to be unique on a per user basis. When a user saves a new post in my Django project, I'd like it to check if the slug exists, and if it does, add a -1 to the end of it. What's the best way to do this? I've added my code below, which is always adding the -1, and I'm sure there's a better way to do this class Post(models.Model): ... def save(self, *args, **kwargs): posts = Post.objects.filter(user=self.user, slug=self.slug) if self not in posts: self.slug = self.slug + '-1' super(Post, self).save(*args, **kwargs) -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
When I tried to add database with inspectdb command then this error is appearing mysql is conencted in settings.py I just created small patient table in phpmyadmin models.py class Patient(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() mobile = models.BigIntegerField() sex = models.CharField(max_length=6) address = models.CharField(max_length=255) occupation = models.CharField(max_length=20) class Meta: managed = False db_table = 'patient' and the remaining is auto generated by django itself there is id column there bt it was not autogenerated and length of age is also not getting fetched so this might causing problem becuz before ruinning inspectdb command server was running normally -
Not sure how to use Tastypie to process in GET and POST with non-standard OMR
I want to know what's best way to handle GET/POST in Tastypie. I am not saving/storing data in database in backend. 2 ajax calls, ajax_get(“GET”), ajax_save(“POST”, big_data>5mb) ajax_save() to save large amount of data. If using GET, nginx, gunicorn has limitation, you have to configure it. I don’t want that, that’s why to use POST. Following could work. But, is there better way? class HelloResource(Resource): file_result = fields.CharField(attribute='file_result', null=True) class Meta: resource_name = ‘hello’ allowed_methods = ('get', 'post') # Make no difference with/without for my case. always_return_data = True max_limit = None limit = 0 def dehydrate(self, bundle): """ Handle ajax POST. """ # When ajax_save() is called, it comes here. # But, the problem is when ajax_get() is called, it also comes to here. # Have to distinguished unrelated call. call_type = bundle.data['type'] # Figure out JS client action. def get_object_list(self, request): """ Handle ajax GET. """ try: # ajax_get(). Works! But, if calling ajax_save(), it does NOT come here. # Therefore, I used dehytrate()!!! call_type = request.GET.get('type', None) # Figure out JS client action. -
Data integrity in JSON(B) when replacing EAV
I'm implementing a database for a new application and I'm considering using JSON fields instead of traditional EAV approach. Everything seems okay, but there is a one big problem that I don't know how to solve. For example; in a traditional EAV model, we would have three tabels; First table to hold the attributes Second table to hold the values Third table to tie those two together. The identifier in the third table would always be primary key of one of the other two and not the value itself. If I change the name of the attribute, it's primary key remains the same thus having no affect on the data integrity in the third table. Now enter JSON. As far as I understand, the whole point of replacing EAV with JSON is to store all the values in the fields itself. So our record could look like this. { "color": "Blue", "size": "Large" } instead of storing values by primary keys. So my question is, if I down the road, change the title of the color from let's say Blue to Purple, how do I deal with data integrity? Since in classic EAV model the primary keys wouldn't change. -
How to refactor two Django querysets that match
I have two models that no have relationship, I match with one of its fields in this case area_ref withresource_ref For example: Match is found: area_ref = 'L020202' with resource_ref = 'L020202' Models... class Area(models.Model): name = models.CharField() area_ref = models.CharField() def __str__(self): return self.name class Resource(models.Model): name = models.CharField() resource_ref = models.CharField() def __str__(self): return self.name I'm currently doing it with lists area = Area.objects.values('area_ref') area_list_ref = [] for _a in area: area_list_ref.append(_a.get('area_ref')) resource = Resource.objects.filter(resource_ref__in=area_list_ref) It works, but when it finds several matches it takes a long time Any better ideas? -
How to check if for loop is in the middle value
I have trouble getting the middle loop in a forloop in django template. I've tried using {% for value in key.dictionary %} {% if forloop.counter == widthratio value|length 2 1 %} but with no effect. Actually after the widthratio I get an error Expected %} Computing the division was taken from this post Is there a filter for divide for Django Template? -
How to get sql equivalent query from django query?
Currently I am developing website in Django & I need to convert some djnago query to sql equivalent query. Purchase_order.objects.filter(query).order_by(id)[start: (start+length)] I want to convert above django query into sql type of query. Is there any way availble to convert it into sql also.