Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I learn .Net or Drupal for web-development?
I just started a new job and I've been asked to develop a web-app and need to decide what development framework (.Net or Drupal) to learn. I apologize if this is the wrong place to post this question. I have experience as a Linux admin, and have written primarily in Python in the past. I have slight familiarity with C++ and Java but greatly prefer Python. I know that my IT department is trending towards a Linux environment (it's mostly windows atm) and I want to develop in something that can potentially migrate from a windows server without having to completely re-write the application. My boss has other ideas, however. If he had his way, I'd be developing in .Net everything for all time. And before he'd let that happen, all my development would be in Access....and I'm not sure I want to do that. I know that there is some development happening with Drupal in our environment elsewhere. It would be nice to have a backup or someone around that can be a reference when I run into issues. Otherwise I'd be the only .Net developer in the org. My predecessor is working part-time as a developer for my … -
Rendering results of multiple value Django annotate query with into html table
I am trying to display a summary of statuses by agent. Annotate looks like the way to go, but the data structure doesn't seem to allow me to loop through the objects and populate an html table cleanly. I've tried manipulating the result set further in my view before passing to the template, but I've mangled it so badly that I'm not sure if I'm approaching this correctly. Any feedback is appreciated. I've attempted the query the database with a 'group by' query using the objects.values().annotate() methods. This outputs a list of dictionaries. If I could get the values as keys, that might work, but there is another list. Querying the user model directly may inadvertently leave out any agents that don't have any QA events. original views.py def agent_summary(request): lead_qas = LeadQA.objects.values('qa_agent', 'qa_status').annotate(Count('id')) context = {'lead_qas': lead_qas} return render(request, 'manager/agent_summary.html', context) This gets me a data structure like: {'qa_agent': 3, 'qa_status': 'Confirmed', 'id__count': 1}, {'qa_agent': 1, 'qa_status': 'Pending Review', 'id__count': 6}, {'qa_agent': 1, 'qa_status': 'Disqualified', 'id__count': 8}, {'qa_agent': 2, 'qa_status': 'Disqualified', 'id__count': 1}, {'qa_agent': 2, 'qa_status': 'Not Started', 'id__count': 4}, {'qa_agent': 1, 'qa_status': 'Not Started', 'id__count': 3}, {'qa_agent': 3, 'qa_status': 'Not Started', 'id__count': 4}, {'qa_agent': 1, 'qa_status': 'Confirmed', 'id__count': … -
About installation issue of postgreSql
When I tried to install Postgre SQL in my windows 8.1 when it almost comes near to complete installation showing this error: Problem Running Post-Install Step. Installation May Not Complete Correctly failed to start the database server. Please, someone, help me in this case ???? error: Problem Running Post-Install Step. Installation May Not Complete Correctly failed to start the database server. -
Django: How to Sum By Range_Date
Filter with the date and find the sum of the range, not the total of all the objects,example, from January 1 until January 2 or from February 1 to February 20, each range. This is my code: def orecerca(request): qs = Ore.objects.filter(user=request.user) sum = Ore.objects.filter(user=request.user).aggregate(totals=(Sum('oret'))) nomecognome = request.GET.get('nomecognome') date_min = request.GET.get('date_min') date_max = request.GET.get('date_max') if is_valid_queryparam(nomecognome): qs = qs.filter(nomecognome=nomecognome) if is_valid_queryparam(date_min): qs = qs.filter(data__gte=date_min) if is_valid_queryparam(date_max): qs = qs.filter(data__lte=date_max) context = { 'ore': qs, 'sum': sum, } return render(request, "guarda.html", context,) -
AttributeError: 'int' object has no attribute 'pk'
I am attempting to create a POST endpoint using DRF ListSerializer to create a list of LogLevel objects. I have tried to serialize the foreign key using PrimaryKeyRelatedField without success. models.py relevant fields for LogLevel model. note foreign key to node model #associated node node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, related_name="log_levels") #logger name name = models.CharField(max_length=32, choices=LOGGERS) # Current log level level = models.IntegerField(default=INFO, choices=LOG_LEVELS) # Timestamps created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True, blank=True, null=True) serializers.py class LogLevelListSerializer(serializers.ListSerializer): def create(self, validated_data): log_levels = [LogLevel(**item) for item in validated_data] levels = LogLevel.objects.bulk_create(log_levels) return levels class LogLevelCreateUpdateSerializer(serializers.ModelSerializer): class Meta: model = LogLevel fields = "__all__" list_serializer_class = LogLevelListSerializer LogLevel view class LogLevelList(MethodSerializerMixin, generics.ListCreateAPIView): """ Log Level list API Endpoint. """ method_serializer_classes = { ("POST",): LogLevelCreateUpdateSerializer } def get_queryset(self): """ Queryset to use for endpoint. """ return LogLevel.objects.all() def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() # check if many is required if "data" in kwargs: data = kwargs["data"] # check if many is required if isinstance(data, list): kwargs["many"] = True return serializer_class(*args, **kwargs) I expect the objects to be created and displayed to … -
MultipleObjectsReturned Django error despite fields being unique together
I have a model called Packaging that is defined in Django as follows using Postgres: class Packaging(BaseModel): unit_of_measure = models.CharField( _("UOM"), max_length=50, null=True, ) quantity_in_unit_of_measure = models.IntegerField( _("Qty In UOM"), null=True, blank=True, ) class Meta(BaseModel.Meta): index_together = [ 'unit_of_measure', 'quantity_in_unit_of_measure' ] unique_together = [ 'unit_of_measure', 'quantity_in_unit_of_measure' ] BaseModel adds some fields like created_by and modified_by. I'm trying to allow multiple Celery threads to call the following function while avoiding duplicate entries: packaging, _ = safe_get_or_create( Packaging, unit_of_measure=description.get('unit_of_measure'), quantity_in_unit_of_measure=description.get( 'quantity_in_unit_of_measure' ) ) Description is a dict that varies with values like the following: { "unit_of_measure": "EA", "quantity_in_unit_of_measure": 1 } The function I'm calling is: def safe_get_or_create(model, **kwargs): ''' the keys of kwargs must be enforced as unique_together in the database ''' try: created = False try: instance = model.objects.get(**kwargs) except model.DoesNotExist: try: with transaction.atomic(): instance = model.objects.create(**kwargs) created = True except IntegrityError: instance = model.objects.get(**kwargs) return instance, created except MultipleObjectsReturned: print(model) print(kwargs) print(model.objects.filter(**kwargs)) print(model.objects.filter(**kwargs).count()) raise Which is based on https://www.agiliq.com/blog/2013/08/writing-thread-safe-django-code/ The error I'm getting and output from that function is: <class 'apps.products.models.Packaging'> {'unit_of_measure': 'EA', 'quantity_in_unit_of_measure': None} <QuerySet [<Packaging: Packaging object (262)>, <Packaging: Packaging object (241)>]> 2 apps.products.models.Packaging.MultipleObjectsReturned: get() returned more than one Packaging -- it returned 2! When I view the … -
Is there a way to pass model attribute into another attribute?
I'm using {% autoescape off %} to render html that I add through admin page. I want to get another variable of the model. post.html {% autoescape off %} {{ post.content }} {% endautoescape %} Is it possible pass another attribute of the same model into the content? Something like that post.content <img src="{{ post.main_image.url }}"> -
Django migrations not pushing to Heroku
I have updated a Django blog to use slug urls <slug:slug>/ instead of id <int:pk>/. I also added a slugField to the Article model, and converted all hrefs to article.slug. Ran migrations and everything worked fine locally. However, when I pushed to Heroku I got the following error. ProgrammingError at /admin/articles/article/ column articles_article.slug does not exist LINE 1: ...ticles_article"."id", "articles_article"."title", "articles_... ^ Request Method: GET Request URL: https://***********.herokuapp.com/admin/articles/article/ Django Version: 2.1.4 Exception Type: ProgrammingError Exception Value: column articles_article.slug does not exist LINE 1: ...ticles_article"."id", "articles_article"."title", "articles_... ^ I checked my Heroku Postgress database and I found that the new slug column hadn't been added even though I did migrations. I'm not exactly sure what to do next. I'm currently searching for ways to manually update the heroku postgress, but if there's a less invasive way to solve this problem I'm all ears. -
Extension of user model in django redux registration gives NotImplementedError at /accounts/register/ error
I am trying to extend the user model in django redux registration. I have tried some possible solutions, but all in vain. Django Debug shows that is "NotImplementedError at /accounts/register/ No exception message supplied" I have tried this to solve this problem Moreover, i was following rvlsico answer here on how to get started on it. Any help would be appreciated. Here are my code snippets: regbackend.py class MyRegistrationView(RegistrationView): form_class = ProfileForm def register(self,form_class): new_user = super(MyRegistrationView, self).register(form_class) p = form_class.cleaned_data['teacher'] new_profile = Profile.objects.create(user=new_user, teacher=p) new_profile.save() return new_user models.py class Profile(models.Model): user = models.OneToOneField(User, primary_key=True,on_delete=models.PROTECT) teacher = models.BooleanField(default=False) @property def is_teacher(self): return self.teacher forms.py class ProfileForm(RegistrationFormUniqueEmail): teacher = forms.BooleanField(required=False,label=("Are you a teacher?")) urls.py urlpatterns = [ re_path(r'^register/$', MyRegistrationView.as_view(), name='registration_register'), path('', include('registration.backends.default.urls')),] -
Django Forms: unique inputs, similar form on same page?
In my admin console - users can upload more than one picture and give each picture a unique slug (site/pictures/slug) - if the user tries to give a picture a slug that already exists by querying the database, they get a validation error telling them to create a unique slug - but if they submit two pictures at the same time with the same slug, theres not such error because the slugs arent in the database yet to raise errors. how do i query the form to make sure two pictures slugs are unique to eachother within the form? def clean_slug(self): slug = self.cleaned_data.get('slug', '').strip() picture_id = self.cleaned_data.get('picture_id') slug_query = Pictures.objects.filter(slug=slug.lower()) if self.instance and self.instance.id: slug_query = slug_query.exclude(id=self.instance.id) if slug.lower() and slug_query.exists(): raise forms.ValidationError('This slug is not unique. Please try a different slug.', code='invalid') return slug.lower() the first if statement is so if a user updates a picture resource, the db wont query the database and say the slug exists. the second prevents none unique slug urls from being added -
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()