Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache Server for Django WSGI
I am trying to set up an Apache mod_wsgi server for my Django project but all I get is a directory of my Django Project to show up and none of my html elements. I don't think my conf file is executing properly. If I put Replicator.com next to 127.0.0.1 then it says internal server error on website/ when check synax(sudo apachectl -t): it says : apache2: Could not reliably determine the server's fully qualified domain name, using 192.168.100.127. Set the 'ServerName' directive globally to suppress this message and same goes if I uncomment 127.0.1.1. Here's my wsgi.py (/var/www/html/Replicator.com/dfp/dfp-rep/djangoprimer) : import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoprimer.settings') application = get_wsgi_application() Here's my /etc/hosts file : 127.0.0.1 localhost.localdomain localhost 192.168.100.127 Replicator.com #127.0.1.1 dfp-S2600CWR # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters Here's my Replicator.conf (/etc/apache2/sites-enabled) : VirtualHost 127.0.0.1:80> ServerName Replicator.com ServerAlias www.Replicator.com DocumentRoot /var/www/html/Replicator.com/dfp/dfp-rep/ WSGIDaemonProcess Replicator.com python-path=/var/www/html/Replicator.com/dfp/d$ WSGIScriptAlias / /var/www/html/Replicator.com/dfp/dfp-rep/djangoprimer/wsgi.py$ process-group=Replicator.com <Directory /var/www/html/Replicator.com/dfp/dfp-rep/djangoprimer> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /var/www/html/Replicator.com/dfp/dfp-rep/static/ <Directory /var/www/html/Replicator.com/dfp/dfp-rep/static/> Require all granted </Directory> </VirtualHost> -
Retrieve stack trace in django Middleware
How can I get the stack trace when something fails on the server side in the django middleware? Here is what I've tried that only gives me the message, not the full stack. class MonitorMiddleware(object): def process_exception(self, request, exception): self.error = exception.message -
How to merge two querysets django
I'm trying to get a list of latest 100 posts and also the aggregated count of approved, pending, and rejected posts for the user of that post. models.py class BlogPost(models.Model): POST_STATUSES = ( ('A', 'Approved'), ('P', 'Pending'), ('R', 'Rejected') ) author = models.ForeignKey(User) title = models.CharField(max_length=50) description = models.TextField() status = models.ChoiceField(max_length=1, choices=POST_STATUSES) views.py Now I'm getting the the aggregated count like so, but I'm confused on how to merge the count with the title of the posts top_post_users = list(BlogPost.objects.values_list('user_id', flat=True))[:100] users = User.objects.filter(pk__in=top_post_users).annotate(approved_count=Count(Case(When(user_posts__status="A", then=1),output_field=IntegerField()))).annotate(pending_count=Count(Case(When(user_posts__status="P", then=1),output_field=IntegerField()))).annotate(reject_count=Count(Case(When(user_posts__status="R", then=1),output_field=IntegerField()))) users.values('approved_count', 'pending_count', 'reject_count') This is the result I want: Title Of Post, Author1, 10, 5, 1 Title Of Post2, Author2, 7, 3, 1 Title Of Post3, Author1, 10, 5, 1 How can I merge the returned counts with the titles? I know I could use a for loop and append each one, but efficiency wise I don't think this is the right way to do it. Is there a more efficient way using django database ORM? I've tried this users.values('title', approved_count', 'pending_count', 'reject_count') ...and that works, but it returns more than the latest 100 posts, so I think it's getting all the posts for those users and the aggregated count. -
NoReverseMatch for rendering a form
I am trying to prepopulate the fields in a form from database. I have an html page and there is a table at which I will click on the link which will render the html form with values populated from the database. But the issue is I am not able to prepopulate the HTML form fields. following is my code and I am not able to get the output. html code in table <td>{{ info.university_code }}</td> <td>{{ info.avg_grescore }}</td> <td>{{ info.avg_english_score }}</td> <td>{{ info.avg_undergradcgpa }} CGPA</td> <td>{{ info.avg_workex_months }} Months</td> <td>{{ info.avg_research_skills }}%</td> <td>{{ info.avg_acceptancepercentage }}</td> <td><a href="{% url 'editSummary' univ_code=info.university_code %}" Views.py(here all my logic is present which is notworking and gives me an error) def editSummary(request,univ_code): if request.method == "POST": form = UniversitySummaryForm(request.POST or None, instance = uiversity) if form.is_valid(): form.save() return redirect('/AdminHome') else: form = UniversityInfoForm() form.fields["university_code"].queryset =UniversityNames.objects.filter(university_code=request.university_code) template_vars = RequestContext(request, { "form": form, "university_code": request.university_code }) return render_to_response("PredictiveAcceptance/AdminUniversitySummary.html", template_vars) Models.py (for database fields) class UniversitySummaries(models.Model): university_code = models.ForeignKey('UniversityNames', models.DO_NOTHING, db_column='university_code', primary_key=True) avg_grescore = models.IntegerField() avg_english_score = models.IntegerField() avg_undergradcgpa = models.IntegerField() avg_workex_months = models.IntegerField() avg_research_skills = models.IntegerField() avg_acceptancepercentage = models.IntegerField() created_on = models.DateTimeField(auto_now_add = True) Forms.py file class UniversitySummaryForm(forms.ModelForm): class Meta: model = UniversitySummaries fields = ('university_code','avg_grescore','avg_english_score','avg_undergradcgpa','avg_workex_months','avg_research_skills','avg_acceptancepercentage') -
How do I get the text value of a selected option in django views.py
For example: if first option Regular is selected then how can i get the value "1" and its text value "Regular" in views.py <form method = "post" action = "{% url 'index' %}"> {% csrf_token %} <select name = "drop1" > <option value="1">Regular</option> <option value="2">Medium</option> <option value="3">Large</option> </select> <input type = "submit" value="Submit"> -
Docker delete file on stop of container
i have a django app that also uses cerlery and celery also creates a .pid file but if i restart my app with docker-compose up celery fails to start because the old .pid file within the container does not get deleted, what can i do to solve this isse? Is there maybe a way on linux-side (debian 9) to remove the file at restart or shutdown of the container? Thanks and br -
DJANGO SURVEY WITH RESULTS IN SQL SERVER
I am new to Django and struggling to create a survey in a django HTML page. Survey results need to be inserted in a SQL Server Database table. The contents of the survey table are part of another table in the same database, but this is not such a big issue as I could easily collect them and transform them in, for example, an HTML table. Could you please give me any ideas on how to tackle this project? Would Django Survey be applicable here? I really hope no other similar posts exists - if so please share them with me! Thanks a lot! Cheers, Alex -
is there a way to override model methods in django?
I have a model like this: class Car(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) create_date = models.DateTimeField('date added', auto_now_add=True) modify_date = models.DateTimeField('date modified', auto_now=True) ... def last_tracked_location(self): ... try: url = 'myurl' return requests.get( url, ).json()['location']) except: return False This method get's called later for the admin's panel. It requests something from an api and then returns either this or false. In testing mode the other api doesn't exist so the request delays all the tests till it timeouts and then returns False. Is there a way to override this? I checked the docs but could only find out to override the settings. Another idea I had was to test inside the method if it's being called in testing mode and then just never go into this try block. But I don't think this is a clean way. -
Django DeleteView not showing errors, but not deleting either
I'm trying to create a one way DeleteView for a Django Channels messaging thread between 2 users. I'm calling DeleteView with a form on the ThreadView page. thread.html <form action="{% url 'chat:thread_delete' thread.second %}" method='post'> {% csrf_token %} <button type='submit' class='btn btn-light'> <i class="fas fa-trash-alt" style="color:royalblue"> </i> </button> </form> The URL changes when I click the form button from http://127.0.0.1:8000/messages/bob/ to http://127.0.0.1:8000/messages/bob/delete/ And there are no errors but nothing happens. The thread page just reloads, messages and all. It doesn't redirect to inbox as I've specified in the success_url. Can someone help? views.py class InboxView(LoginRequiredMixin, ListView): template_name = 'chat/inbox.html' context_object_name = 'threads' def get_queryset(self): return Thread.objects.by_user(self.request.user).exclude(chatmessage__isnull=True).order_by('-timestamp') # by_user(self.request.user) class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'chat/thread.html' form_class = ComposeForm success_url = '#' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_object(self): other_username = self.kwargs.get("username") obj, created = Thread.objects.get_or_new(self.request.user, other_username) if obj == None: raise Http404 return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): thread = self.get_object() user = self.request.user message = form.cleaned_data.get("message") ChatMessage.objects.create(user=user, thread=thread, message=message) return super().form_valid(form) class ThreadDeleteView(DeleteView): model = Thread success_url … -
Celery task running before ETA
I have a celery task that spawns a celery task that should run at a certain hour, by using the eta parameter. Here's a sample task: @celery_app.task() def spawners_for_tasks(): # I set the eta to the target timezone's current hour, but with 59 for the minute # this is just for testing, and gives me a 1/60 chance that the other task shouldn't be spawned yet eta = datetime.now(pytz.timezone("Africa/Djibouti")).replace(minute=59) do_other_task.apply_async((1,), eta=eta) Which spawns this task: @celery_app.task() def do_other_task(task_id): pass The do_other_task task gets called immediately. I've tried using CELERY_ALWAYS_EAGER as True and False, and I've tried converting the eta into UTC time and just replacing the current tz info with the target tz(eta.replace(tzinfo=pytz.timezone("Africa/Djibouti"))) -
Celery delete old pickle
I'm working on some celery tasks and was messing around with a custom Schedule object, but then deleted it. I put it in the same file as my celeryapp.py file, so maybe that was the issue, but now every time I run celery -A <app> worker -l info -B I get a notification about the missing object. I've tried purging the queue, but that doesn't seem to help. It appears that I need to remove the old pickle file, but I can't figure out where the pickle file is to even delete it. This is on my local test system, so I'm not concerned about data loss. I'm using Django 2.1, Celery 4.2, Python 3.5. Error I'm getting from celery beat: [2019-03-20 18:22:26,668: WARNING/Beat] AttributeError: Can't get attribute 'TaskNotificationSchedule' -
Django logout page not found in windows but it working in mac
The code is working on mac but in windows when I logout it saying page not found. from django.urls import path from.import views from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView urlpatterns = [ path('login/', LoginView.as_view(template_name='registration/login.html'), name="login"), path('logout/', LogoutView.as_view(template_name='upload.html'), name="logout"), path('signup/', views.signup, name='signup'), path('resetpassword/', PasswordResetView, name="resetpassword") ] -
djanga rest framwork: 'str' object has no attribute 'pk'
I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have composite pk on my table TestSuite. When I do a get() on the test_suites it throws an error - 'str' object has no attribute 'pk' . I haven't defined pk in my model, as with django I cannot define composite primary keys. Hence, django uses 'id' an autogenerated pk for the model. I cannot add id in my database (as I cannot modify the db). The post() works as expected, however get() is throwing error through postman() as well as browsable API. I am new to DRF. Any help is appreciated. DB create statement: CREATE TABLE `test_suite` ( `team_name` varchar(30) NOT NULL, `suite_name` varchar(100) NOT NULL, `description` varchar(200) DEFAULT NULL, `schedule` varchar(100) DEFAULT NULL, `email_list_ok` varchar(200) DEFAULT NULL, `email_list_fail` varchar(200) DEFAULT NULL, `template_name` varchar(100) NOT NULL, PRIMARY KEY (`team_name`,`suite_name`), KEY `fk_test_suite__email_templates` (`template_name`), CONSTRAINT `fk_test_suite__email_templates` FOREIGN KEY (`template_name`) REFERENCES `email_templates` (`template_name`), CONSTRAINT `fk_test_suite__team` FOREIGN KEY (`team_name`) REFERENCES `team` (`team_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; I need to do a get() and post() to this table. Below are my models , serializers and viewsets. models.py class Team(models.Model): team_name = models.CharField(primary_key=True, max_length=30) description = models.CharField(max_length=100, … -
Django displayed default form errors
First of all, my apologize for mistakes in English. I was trying to add some changes in displaying of form errors. Error in forms According to my pict I have 2 types of errors right now. First line of error is that I want and second line is default line of form errors. How can I remove second line of error (default error)? part of html code where is form {% load crispy_forms_tags %} <div class = 'container mt-4 sidebar-form'> <h3 class = 'text-center mt-3'>{{ form_title }}</h3> <hr> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <form method = 'POST'action = '' class = 'form-group' enctype = 'multipart/form-data'> {% csrf_token %} {{ form|crispy }} <button class = 'btn btn-outline-info' type = 'Submit'>{{ form_buttom }}</button> <a href="" id="cancel" name="cancel" class="btn btn-primary">Cancel</a> </form> </div> views.py class GenreUpdate(View): model = Genre template_name = 'core/detail.html' form = GenreForm title = 'Genre' form_title = 'Edit Genre' form_buttom = 'Save' sub_category = 'Genre' def get(self, request, … -
Why are the different fields of a Django model class not instance attributes?
In a Django model class, we define the different fields to be class attributes. However, when we create multiple objects of this class corresponding to multiple rows of a table, we pass keyword arguments of the same name as the class variables to instantiate the class' object. What purpose then does having the different fields as class attributes serve? Edit: The question here: Django: why are Django model fields class attributes? is similar to mine, but the answer doesnt address my doubts. The answer mostly just goes into how attribute lookup works and namespaces. What I want to know is why do we not have an init function in the model class for the different fields of the model. Even if the class attributes are used internally by the ORM(as the answer to the linked question says), that doesnt explain how when creating new instances of the model class, the field names for the model show up in the dict attribute for that object. What I'm looking for is: what happens internally so that when the model class is instantiated WITHOUT an init method that allows the passed keyword args to be added to the dict attribute ? -
GeoDjango OSMWidget coordinate change
I want to know if there's a way to know when the OSMWidget coordinates have been changed, I'm pretending to reflect this change on the Longitude and Latitude fields. I have the following form: from django.contrib.gis import forms from .models import Branch class BranchCreateForm(forms.Form): name = forms.CharField(label ="Name", max_length=120) image_facade = forms.ImageField( label="Image Facade") longitude = forms.DecimalField(label = "Latitude", max_digits=9, decimal_places=6) latitude = forms.DecimalField(label = "Longitude", max_digits=9, decimal_places=6) location = forms.PointField( widget=forms.OSMWidget( attrs={'map_width': 600, 'map_height': 400, 'template_name': 'gis/openlayers-osm.html', 'default_lat': 42.1710962, 'default_lon': 18.8062112, 'default_zoom': 6})) -
coverage badge is stuck on "unknown"
I am trying to use coveralls.io to show a coverage badge for my tests, but the coverage badge is stuck on "unknown". The relevant repo is here: https://github.com/Noah-Lc/simple-blog-rest-api When I look at coveralls.io for that repo I see the same "coverage: unknown" status: However, the individual builds are being correctly sent to coveralls.io: https://coveralls.io/jobs/46387537 -
Manage a multi-group application in django using a middleware
I'm quite new to django. Me and my team are working on a django (vers. 2.1.7 with python 3.5.2) application. The application is currently used by a group of people (i'll call this group A), but the idea is to manage several different groups (B, C, etc), so that every group will be able to see only the data under their sphere of. In other words, we have to build a multi-platform architecture, with just one server, one domain and one db. The trivial (but long and boring) way to do so would probably be something like this: Add a "platform" field to every relevant model (and migrate), and set a default value equals to the current existing platform. Change all the "select" queries so to filter the results according to the current user's platform. Change all the "write" queries so to set the correct value in the "platform" column. A co-worker suggested that it may be possible to define a middleware that would handle the second and third steps, but i'm quite puzzled and not very sure that this could be possible. I'm not a django expert by any mean I'd like to know if you think it is … -
How to make django-rules work in templates?
When using Django-Rules, you can check permissions in views. But mine always returns false. Code in example below always displays 'bar', but must display 'foo': {% extends 'home/base.html' %} {% load rules %} {% has_perm 'anApp.can_access_something' user as can_access_something %} {% block content %} {% if can_access_something %} <p>foo</p> {% else %} <p>bar</p> {% endif %} ... {% endblock %} My rules.py looks like this: @rules.predicate def testrule(user): return True rules.add_perm('anApp.can_access_something', testrule) So will always return true. -
Django foreign-key many to one relationship displaying on template
I'm trying to display job offers that are in relation ship with Company (Many To One) but I'm not able to do it. I've tried many loops but I'm not even getting queryset so I must doing it wrong but can't solve what I'm doing wrong. My files models.py class Company(models.Model): # field person with relation many to one (many persons to 1 company) team = models.ManyToManyField('Person') name = models.CharField(max_length=100, blank=False) ... class Job(models.Model): name = models.CharField(max_length=40, blank=False) level = models.CharField(max_length=10, blank=False, choices=LEVELS) company = models.ForeignKey('Company', on_delete=models.CASCADE, default=None, blank=False) emp_type = models.ManyToManyField('Emp_type', blank=False) ... def __str__(self): return self.name comp_list.html <div class="company-logo-container"> <img class="company-logo" src="{{ brand.logo.url }}"> </div> <ul class="list-group"> <li class="list-group-item"> <a class="nav-link" href="#team">Team</a> </li> <li class="list-group-item"> <a class="nav-link" href="#social_media">Social Media</a> </li> <li class="list-group-item"> <a class="nav-link" href="#offers">Job Offers</a> </li> {% for job in jobs %} {% for company in job.company.all %} {{ job.name }} {% endfor %} {% endfor %} </ul> views.py def brands(request, slug): brand = get_object_or_404(Company, slug=slug) return render(request, 'company/comp_view.html', {'brand': brand}) def jobs(request, slug): job = get_object_or_404(Job, slug=slug) return render(request, 'company/job_view.html', {'job': job}) I've created few job offers and assigned them to 1 company but I'm not able to get them in company view so its look … -
How to get the current user to add it to a form
So here's my problem, I'm trying to get the currently logged in user to put in a manytomanyfield field when processing a form. Models.py The model contains a field contributors in manytomanyfield class Property(models.Model): title = models.CharField(max_length=250,verbose_name="Nom de l'établissement") contributors = models.ManyToManyField(User, verbose_name="Liste des collaborateurs autorisés") # ManyToMany pour autoriser plusieurs "User" à y accéder token = models.CharField(max_length=500,verbose_name="Token") # Token généré par nous ou via un app secret key payday = models.CharField(max_length=500,verbose_name="Jour de paye", null=True, blank=True) planning = models.ImageField('Planning', null=True, blank=True ) def __str__(self): return self.title def get_absolute_url(self): return reverse('property-home') The ModelForm For the creation of a property I simply display the title field class CreateProperty(forms.ModelForm): class Meta: model = Property fields = ['title',] And processing the form (views.py) I'm trying to add the id of the currently logged in user via request.user.pk def create_property(request): if request.method == "POST": form = CreateProperty(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.token = 'TOKEN_GENERATOR_SIMULATION' instance.contributors = request.user.pk instance.save() messages.success(request, _(f"good")) return redirect('create-property') else: messages.error(request, _(f"The form is invalid")) return HttpResponseRedirect(reverse('create-property')) else: form = CreateProperty(instance=request.user) form.contributors = request.user args = {'form': form} return render(request, 'create_property.html', args) But when I try to create a property I come across an error: TypeError at /property/create Direct assignment to … -
Django: Is it possible to use AJAX to save an object without page refresh, and then display the object saved?
I have a django form for which I use AJAX to save the form object, and then refresh the form into an empty one. I then want to be able to display the saved form object from the AJAX call. Is this possible in django template? Is it possible to do a 'partial refresh'? -
Django TemplateView Context Not Rendering on Template
I know this has probably been asked a million times, but I searched forever and couldn't find an answer. I'm trying to create several select drop downs to use as a search filter on my index page. I have loaded the models with data, but when I try to render the data on the template, I'm not seeing what is in the model. Here is my code: views.py from django.views.generic import TemplateView from .models import LengthRange, Hull class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['length_ranges'] = LengthRange.objects.all() context['hull_types'] = Hull.objects.all() return context urls.py from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name='index.html'), name='index'), ] and my snippet from index.html: <h2 class="about-item__text"> A boat with a length of <select> <option value="*" selected>any size</option> {% for length in length_ranges %} <option value="{{ length.pk }}">{{ length.range }}</option> {% endfor %} </select> , with hull type of <select> <option value="*" selected>any</option> {% for hull in hull_types %} <option value="{{ hull.pk }}">{{ hull.type }}</option> {% endfor %} </select> It's been a really long time since I worked in Django, but this should have been relatively easy. What am I missing here? -
Django model id is not auto-incrementing
I am trying create a new database entry using a custom Django model I created. However, when I try to create the model and save it, the id does not increment. Instead, the previous database entry is overwritten whose id == 1. I have tried setting force_insert=True inside the save() function, but it results in a runtime error where the primary key already exists. I don't set any primary values in the creation of the object, so I'm not sure why the id is not being incremented. I am running the test code in the manage.py shell. All the models have been migrated properly. The model: class RoadWayData(models.Model): blocked_lanes = models.PositiveIntegerField() city = models.CharField(max_length=255) county = models.CharField(max_length=255) direction = models.CharField(max_length=255, blank=True, null=True, default=None) eto = models.CharField(max_length=255) incident_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) incident_object = GenericForeignKey('incident_type', 'id') injuries = models.PositiveIntegerField() postmile = models.CharField(max_length=255, blank=True, null=True, default=None) queue = models.CharField(max_length=255, default="NONE: Freeflow Conditions") route = models.CharField(max_length=255, blank=True, null=True, default=None) street = models.CharField(max_length=255, blank=True, null=True, default=None) timestamp = models.DateTimeField(auto_now=True) update = models.PositiveIntegerField() maintenance = models.CharField(max_length=255) tow = models.CharField(max_length=255) weather = models.CharField(max_length=255) vehicles_involved = models.PositiveIntegerField() The test code: from incident.models import * import datetime x = IncidentIndex.objects.get(id=1) y = CHPIncident.objects.get(id=x.incident_object.id) print("ID already exists in DB: {}".format(RoadWayData.objects.get(id=1).id)) … -
AttributeError: 'tuple' object has no attribute 'client'
im trying to access a cached_property from a model and its returning 'tuple' object has no attribute 'client' this is the model that has the cached_property class Creds(models.Model): tenant = models.OneToOneField('tenant.Tenant', unique=True, on_delete=models.CASCADE) @cached_property def client(self): from pos.api_client import APIClient return APIClient(self) and here is where im trying to access the cached_property. and getting the error. class createCred(APIView): def get(self, request, *args, **kwargs): tenant = get_object_or_404(Tenant, pk=request['tenant_id']) square_credential = SquareCredential.objects.get_or_create(tenant=tenant) client = square_credential.client