Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make different size image and store them in django?
I am new to Django and I searched but couldn't really find what I want. My problem is. There is a form where a user can upload the image. What I want is, I want to create different size of that image and store them in a database . I used sorl-thumbnail and created the different sizes images to display in the template but I couldn't find the way to store them? {%for hotel in hotel_images %} <div class="container"> <h2>Card Image</h2> <div class="card" style="width:400px"> {% thumbnail hotel.hotel_Main_Img "100x100" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} <div class="card-body"> <h4 class="card-title">{{hotel.name}}</h4> <a href="#" class="btn btn-primary">See Profile</a> </div> </div> </div> {% endfor %} -
Installing Coverage.py - No matching distribution found
I'm working on a Django project and want to set up Coverage on my project. $ pip install coverage Could not find a version that satisfies the requirement coverage (from versions: ) No matching distribution found for coverage Does this error mean the package is no longer supported? Just wondering what I should try to get this installed. Thanks in advanced! -
Best practice for handling user permissions in DRF
Let imagine I would like to create an API with CRUD operations and some custom methods. I would like to customize permissions, provided by django rest framework for solve following tasks: I would like to specify user permission for CRUD operations. For example John could create an instance of Foo entity, but Sara could only read objects I would like to specify user permissions for my custom methods. For example Mikle can publish Foo objects. What is the best practice for working with permissions? Should I define permission classes in every API methods that is connected with my model? What if I have several methods that can provide a the same request type on the same model?SHould I copypaste code? Or there is a way to define base permissions on model-level and then specify some concrete implementation in views? For example Foo object consists of 100 attributes, there is 10 methods for getting some parts of it. I would like to allow Mike do perform GET request once in a model, not 10 times in each view. class Foo(): attr1 = ... .... attr100 = .... class FooSerializerBase(): ... fields = '__all__' class FooSerializer_1(): ... fields = ['attr1, attr2, attr3...attr10'] … -
How to update specific model fields using Django UpdateView
How can you update certain model fields when a form is posted using Django's UpdateView? When the user checks complete = True on the form, and submits it, I want their name and date to be saved to this record (fields not visible on the form). The code below isn't throwing any errors, but it also isn't updating the fields requested. view: class maintenanceEdit(LoginRequiredMixin,UpdateView,): model = Maintenance form_class = EditMaintenance template_name = 'maintenance_edit.html' login_url = 'login' success_url = reverse_lazy('equipmentdashboard') def form_valid(self, form,): instance = form.save(commit=False) instance.user = self.request.user user = instance.user.first_name +" "+instance.user.last_name completed = form.instance.completed dateCompleted = form.instance.dateCompleted if (dateCompleted is None): if completed == True: updateMaintenance = Maintenance.objects.get(id = instance.id) updateMaintenance.dateCompleted = timezone.now() updateMaintenance.completedBy = user updateMaintenance.save(update_fields=['dateCompleted','completedBy',]) return super(maintenanceEdit, self).form_valid(form) model: class Maintenance(models.Model): device = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,) customerTag = models.CharField(max_length=50,) maintenanceItem = models.CharField(max_length=35,blank=True,) maintenanceDescrip = models.TextField(max_length=300,blank=True,) maintenanceNotes = models.TextField(max_length=300,blank=True,) dateCreated = models.DateTimeField(auto_now_add=True,) dateDue = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True) dateCompleted = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True) completed = models.BooleanField(default = False) createdBy = models.CharField(max_length=35,blank=True,) completedBy = models.CharField(max_length=35,blank=True,) form: class EditMaintenance(forms.ModelForm): def __init__(self, *args, **kwargs): super(EditMaintenance, self).__init__(*args, **kwargs) self.fields['maintenanceItem'].required = True self.fields['dateDue'].required = True class Meta: model = Maintenance fields = ['maintenanceItem','dateDue','maintenanceDescrip', 'maintenanceNotes','completed',] labels = { 'maintenanceItem': ('Maintenance Item'), 'dateDue': … -
Django re_path regex didn't match
The Django Url pattern didn't match. Can someone tell me why? This is the re_path: re_path(r'^resultcount/(?P.*)_()/$', views.resultcount, name='resultcount'), I tried with this URL: http://127.0.0.1:8000/resultcount/Test_(89) -
static files do not load in django
I can load static files perfectly on the home screen, but when I change the page url they are no longer loaded ex "http://localhost:8000" loads perfectly "http://localhost:8000/register" stops loading because you try to get the static files from "/register/static/css" -
NOT NULL constraint failed:
I'm trying to save a Django form, but I keep getting this error: NOT NULL constraint failed: catalog_agreements.agreement The user model in my app is the default Django user model and I'm using Django 2.2.3. I initially thought it was a migrations issue, but I deleted and reran all migrations for the app and it did not fix the issue. Not sure, how it could be not null because the prior page, we register the user and before that there is no user essentially. Here is my views.py: def agreements_page(request): if request.method == "POST": form = AgreementsForm(request.POST) if form.is_valid(): user = request.user if user.is_authenticated: agree = form.save(commit=False) agree.user = request.user agree.save() messages.success(request, f'Yay!') return redirect('other') else: return redirect('other') else: form = AgreementsForm() return render(request, 'agreements_page.html', {'form': form}) Here is my forms.py: class AgreementsForm(forms.ModelForm): agreement = forms.BooleanField(label='I agree to the Terms of Service and Privacy Policy of this site.') class Meta: model = Agreements fields = ('agreement') def agreements(self): agreement = self.cleaned_data.get('agreement') if agreement is False: raise forms.ValidationError("You must agree to all Terms and Conditions.") return agreement def save(self, commit=True): agree = super(AgreementsForm, self).save(commit=False) agree.agreements = self.cleaned_data.get('agreements') if commit: agree.save() return agree Here is my models.py: class Agreements(models.Model): user = models.ForeignKey(User, … -
AJAX Overriding Select Field Required Constraint
I have an AJAX script which dynamically fetches data and populates select field options upon user interaction. However, when the script replaces the contents of the select field, the required tag is being nullified and users are able to submit the form incomplete. How can I make sure the required constraint remains intact when the options are populated? template.html <div class="select"> <select name="select_companies" id="select_companies" required> <option value="" selected disabled>Company</option> {% for company in companies %} <option value="{{ company.id }}" name="selected_company" id="selected_company">{{ company.name }}</option>} {% endfor %} </select> </div> <div class="select"> <select name="select_contacts" id="select_contacts" required> <option value="" selected disabled>Contact</option> {% for contact in contacts %} <option value="{{ contact.id }}" name="selected_contact" id="selected_contact">{{ contact.firstName }} {{ contact.lastName }}</option> {% endfor %} </select> </div> ajax <script> $("#select_companies").change(function () { var contact_url = $("#newOpportunityForm").attr("data-contact-url"); var optionSelected = $(this).find("option:selected"); var company = optionSelected.text(); $.ajax({ url: contact_url, data: { 'selected_company': company }, success: function (data) { console.log(data) $("#select_contacts").html(data); } }); }); </script> -
div CSS loading animation isn't showing?
I have a page where were users click a button to submit a data to be processed the problem is this takes up to 30-40 secs so I want to prevent users to re-click the button again so I made a CSS loading animation in a div and call it in a js script tag but when I try running the js function it doesn't work i even tried running it in the console. <div class="loading" id="q11" style="display:none"> <div class="obj"></div> <div class="obj"></div> <div class="obj"></div> <div class="obj"></div> <div class="obj"></div> <div class="obj"></div> <div class="obj"></div> <div class="obj"></div> </div> <script> $(document).ready(function() { $('#q12').click(function() { $('#q11').show(); }); }); </script> <a href="{% url 'patients:analyse_images' image.pk %}" class="btn btn-sm btn-outline-primary" id="q12">Analyse</a> -
Django imports best practice
I'm a junior django developer and I have a question. I have a project that has many apps (eg. one, two, three). I used to import the other models from other apps and use them on a field that needs to be a foreign key like this from first_app.models import One from second_app.models import Two class Three(models.Model): one = models.ForeignKey(One, on_delete=models.CASCADE) two = models.ForeignKey(Two, on_delete=models.CASCADE) Someone said that it may cause a circular model import issue so I deleted all the imports from the other apps then use it in models like this class Three(models.Model): one = models.ForeignKey('first_app.One', on_delete=models.CASCADE) two = models.ForeignKey('second_app.Two', on_delete=models.CASCADE) Which is the best practice about this one? or when to use the first or second one? Thank you! -
Advice on Achieving Location Based Search in Django
I’m currently developing an application in Django, and I want to give users the ability to enter a location and get matched with any listings (objects in the database) that match the location the user has entered. Very similar to what you might see on many sites across the web such as Airbnb or Zillow. I have looked into GeoDjango, but just could help but think there must be a simpler way to do this. Could I successfully achieve this with an API, or would I need to go the GeoDjango route? Any advice or solutions whatsoever would be deeply appreciated. Thank you! -
Is there a way to group a queryset after filter?
I have to generate 3 data tables. Each one grouped by a different value of a same queryset. I filtered the objects with django_filters. form_filter = PosicaoEstoqueFilter(request.GET, queryset=registros, request=request) After that, I need to group the result 3 times. I tried something like: por_tipo = form_filter.qs.values('produto__tipo').annotate(soma=Sum('saldoatual')) por_cc = form_filter.qs.values('produto__centrocusto').annotate(soma=Sum('saldoatual')) por_grupo = form_filter.qs.values('produto__grupo').annotate(soma=Sum('saldoatual')) But it didn't group. -
Storing to database from Ajax with JavaScript data in Django
I'm learning JavaScript, Ajax and Django. I'm working an quiz. It has a HTML form that carries the questions and a script written in JavaScript that computes the score. The form displays correctly and the JavaScript works perfectly well. It give me the required result. What I'm not getting is the data being stored into the database using Ajax. It doesn't work. Maybe it's the way I'm doing it, but I can't figure this one out. The JavaScript code looks like this (the score variable carries the actual users score). I actually have no issues with it, but it might be helpful for solving my problem. function submitAnswers(answers) { var total = answers.length; var score = 0; var choice = [] //getting choices //new dynamic method 1 for (var i = 1; i <= total; i++) { choice[i] = document.forms["quizForm"]["q" + i].value; } //validation for (i = 1; i <= total; i++) { if (choice[i] == null || choice[i] == '') { alert('You have not answered question ' + i); return false; } } //set correct answer //this variable is replaced by database answer //check answer // new dynamic method 1 for checking answer for (i = 1; i <= … -
Periodic task to pull data from API in Django application
In my Django application, how can I periodically (say every 10 seconds) make a request to an API? Right now I have setup a cron that takes care of making an API call and updating the data, but cron has a minute precision. I want the data to be updated every 10 seconds. -
What is the difference between these two paths in urlpatterns?
urlpatterns = [ path('admin/', admin.site.urls), path('job', jobs.views.home, name='home'), path('job/', include('jobs.urls')), ] What is the difference between the two paths? When should I use jobs.views.home and when should I use the include() -
How do you hand off a website built from django to a client?
After you are finished with a website, how do you transfer the website to your client online via internet so that the client can effectively understand and use the website? -
'view' didn't return an HttpResponse object. It returned None instead.` - class based view
I am trying to access the posted form values in a class based Django view (UpdateView). I have it nearly working, but I am getting the error: The view maintenance.views.maintenanceEdit didn't return an HttpResponse object. It returned None instead. I have found many other posts having the same problem with a function based view, which return render(request, 'template.html') fixes the problem, but how can I do the same thing with a class based view? my views.py: class maintenanceEdit(LoginRequiredMixin,UpdateView,): model = Maintenance form_class = EditMaintenance template_name = 'maintenance_edit.html' login_url = 'login' def form_valid(self, form,): instance = form.save(commit=False) complete = form.instance.completed super(maintenanceEdit, self).form_valid(form) In my models.py I have: def get_absolute_url(self): return reverse('equipmentdashboard',) Which brings the user back to the correct page when the form is submitted. But now this is not working... -
Ways to create reusable sets of fields in Wagtail?
I'm evaluating Wagtail to see if I can find a place for it along side Wordpress and Drupal in my company. So far I think it's interesting and really like a lot of it, but there's one thing I would really like and can't find a way to do it. My shop uses a pattern library (a la Atomic Design) and initially I was excited by the StreamField and it's ability to tie directly in to a pattern library, including creating nested patterns (a reusable button class that can be put in a CTA and a Hero Widget. But the stream field doesn't work for required page elements that have to be in a certain location, possibly outside the content flow (hero content, calls to action...). I found this issue: https://github.com/wagtail/wagtail/issues/2048 But it doesn't seem to be resolved and hasn't had activity in a long time. Right now I've found two possible solutions: A stream field with only one block possible, and a min and max of one of them. The drawback is that the UI doesn't seem to be aware of the min/max and you have to save the page before you're told. Also, the form isn't automatically visible, … -
How do I condense annotated queryset results based on a particular field?
Here's a fun one. Maybe someone can figure this out. Say I have a queryset something like the one below and want to get leads by month per company. Company.objects.annotate( month=TruncMonth('leads__date_received') count=Count('leads') ).values('company__name', 'month', 'count') This will give me one dict per month for each company, something like this: {'company_name': 'Amazon', 'month': '2018-01-01', 'count': 333}, {'company_name': 'Amazon', 'month': '2018-02-01', 'count': 444}, {'company_name': 'Amazon', 'month': '2018-03-01', 'count': 555}, This is great but requires further processing if I want to put this in tabular form. What I would like is a result like the following: {'company_name': 'Amazon', '2018-01-01': 333, '2018-02-01': 444, '2018-03-01': 555} This is ideal if I already know the month range and can pull out each column value on the basis of the month key. Anyone know a slick way of condensing results like this? Is there some already-built auxiliary function that can do this? Any simple database tricks? Curious to hear. -
/post/how-to-write-a-pattern-to-accept-this-kind_of_url (In Django)
I'm trying to achieve a product URL as shown below: base_url/product/this-is-sample-of-product-1 URL can have a combination of the hyphen, underscore, a-zA-Z,0-9 (Similar to the url of posts as in wordpress) Please help, How to achieve this in urls.py - Django. I have tried this code in my urls.py but it is not working. url(r'^product/([-\w]+)/$', include('product.urls')), -
unique constrain fails with foreignKey field
I want to make a position model with a foreign key to a category model, but i get a unique constrain error when adding 2 position to one category although the category field is foreignkey model not one-to-one field i tried many things but it didn't work class Category(models.Model): name = models.CharField(max_length=50, unique=True) _type = models.CharField(max_length=20, null=True) class Position(models.Model): name = models.CharField(max_length=50, unique=True) category = models.IntegerField(Category, on_delete=models.CASCADE) -
DRF Reverse Not Finding Proper Route
I am using Django Rest Framework and I cannot get reverse() to return the proper route for testing purposes. I must have made a mistake somewhere along the path of registering my routes but I can't seem to figure out what it is. core/urls.py class CoreRouter(DefaultRouter): def __init__(self): super(DefaultRouter, self).__init__() self.trailing_slash = '/?' router = CoreRouter() router.register(r'works', WorkViewSet, base_name='work') router.registry.extend(fairs_exhibitions_router.registry) urlpatterns = [ re_path(r'^api/(?P<version>(v1))/', include(router.urls)), re_path(r'^api/(?P<version>(v1))/', include('fairs_exhibitions.urls')), ] fairs_exhibitions/urls.py: router = CoreRouter() router.register(r'fairs', FairTagViewSet, base_name='fair') router.register(r'exhibitions', ExhibitionTagViewSet, base_name='exhibition') urlpatterns = [ url(r'^', include(router.urls)), ] (I ommited includes/a couple of unrelated routes) I can hit api/v1/fairs just fine but when i try to use reverse() i cant seem to find the fairs path: reverse(fairs) or reverse(fairs-list) just says it's not found The closest I got was reverse('fair-list') which yielded this error: NoReverseMatch: Reverse for 'fair-list' with no arguments not found. 4 pattern(s) tried: ['api/(?P(v1))/fairs/?\.(?P[a-z0-9]+)/?$', 'api/(?P(v1))/fairs/?$', 'api/(?P(v1))/fairs/?\.(?P[a-z0-9]+)/?$', 'api/(?P(v1))/fairs/?$'] It seems like my issue might have something to do with the ?$ but I cant figure out where that is coming from or how to handle it. -
DisallowedHost at / Invalid HTTP_HOST header when domain name already exists in ALLOWED_HOSTS
i have purchased my domain from godaddy.com and made it work for my digital ocean droplet. afteri added the domain to "sites-available" for nginx and refreshed the page i got the "disallowed host" error. I already have the domain name in ALLOWED_HOSTS but i still see the "disallowed host" error. -
Django React Project structure that scale
I am so exhausted finding repository to get best Django Rest API and ReactJs project structure. I am integrating Django witht ReactJS. I am struggling to structure my project that is easy to scale. Can any Django-React Developer suggest me a porject structure that is easy to scale and manage? Git link would be much appreciated. I found huge Django-React Project and i am confused which one should i follow. I need best one to structure Django-React project and that is scale-able -
Django's str(queryset.query) returns invalid SQL if I compare datetimes
I have a Django queryset that I prepare with queryset.filter(date__gte=datetime(2011,1,1)) If I then call str(queryset.query) I see this in the string: ... WHERE "App_table"."date" >= 2011-1-1 However, this is invalid SQL code as if I run this in Postgresql I get this error: ... WHERE "App_table"."date" >= 2011-1-1 ERROR: operator does not exist: date >= integer HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Why is this happening and how can I ask Django to output proper SQL code that I can work on?