Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bad version of Django
trying to install https://github.com/sio2project/oioioi (Manual Installation). And after launching oioioi-create-config deployment, I received an error: Traceback (most recent call last): File "/home/oioioi/sio2/venv/bin/oioioi-create-config", line 6, in <module> from pkg_resources import load_entry_point File "/home/oioioi/sio2/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3105, in <module> @_call_aside File "/home/oioioi/sio2/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3089, in _call_aside f(*args, **kwargs) File "/home/oioioi/sio2/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3118, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/home/oioioi/sio2/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 580, in _build_master return cls._build_from_requirements(__requires__) File "/home/oioioi/sio2/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 593, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/home/oioioi/sio2/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 786, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.ContextualVersionConflict: (Django 1.9.13 (/home/oioioi/sio2/venv/lib/python2.7/site-packages), Requirement.parse('django>=1.11'), set(['django-otp'])) . From what I read, django-otp requires the Django version 1.11, but the application itself requires 1.9.13 and installed it. When he tries to reinstall it on 1.11 it also does not work just now in the other direction. I tried to reinstall django-otp to 0.3.3 and then I had to django-two-factor-auth, and when this application required a newer version and we have a circle. I looked at the intenet how to install two versions of Django, but it requires two virtualenv, and here I can not. What to do? Regards and sorry for my English. -
How to create chat application without creating new chat instances between same users
I want to create simple chat application between users.Here is part of the code: Models.py: class Chat(models.Model): message = models.CharField(max_length=250) sender = models.ForeignKey(User,related_name="sent",on_delete=models.CASCADE) receiver = models.ForeignKey(User,related_name="received",on_delete=models.CASCADE) timeStamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) Views.py: def inbox(request): sent_list = Chat.objects.filter(sender=request.user) received_list = Chat.objects.filter(receiver=request.user) inbox_list = sent_list | received_list context={ 'inbox_list':inbox_list } return render(request,'blog/inbox.html',context) Inbox.html: {%for message in inbox_list %} {% if message.sender == request.user %} <a href="{% url 'chat' message.receiver.id %}" >{{message.receiver.username}}</a> {%else%} <a href="{% url 'chat' message.sender.id %}" >{{message.sender.username}}</a> {% endif%} {% endfor%} I get the chatters list in Inbox.html but for each message same user appear in list. How to filter the users only once that i have sent/received message. Also if it is possible to create unique chat room,any recommendation would be useful. -
For 'model_object' in 'query_set_list' is showing empty. Django 1.11
I'm getting started with Django and I'm having some trouble with query_sets and for loops. I have created a model and populated my DB with a few entries. In my views.py I have sent a count of these entries to my template and can see the result in HTML. However when I send a query_set list of these entries I cannot seem to access them and I am unsure as to why. Here is the view.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from website.models import Member # Create your views here. def index(request): """ View for the homepage of the site """ num_mem = Member.objects.count() mem_list = list(Member.objects.all()) context = { 'mem_list': mem_list, 'num_mem' : num_mem, } #render the HTML template index.html with the data return render(request, 'index.html', context=context) In index.html I attempt to access these as such. {% extends "base_generic.html" %} {% block content %} {{ num_mem }} {% for member in mem_list %} There are Members! {% empty %} Sorry can't find the members =/ {% endfor %} {% endblock %} The result returned is as shown. "6 Sorry can't find the members =/" So I can see the mem_count value … -
Using full calendar in django admin; Saving the external dragged item to a model
i have set up fullcalendar inside my admin, so i can drag timeslot on the calendar to select which date/timeslots are available for my clients to book, the calendar work perfectly, the drag items are fine, but when i put them in the calendar, it doesnt save to my model and to database. here is the code. model: class Event(models.Model): event_name = models.CharField(max_length=255,null=True,blank=True) start = models.DateTimeField(null=True,blank=True) end = models.DateTimeField(null=True,blank=True) available = models.BooleanField(default=True) patient_name = models.CharField(max_length=60, null=True, blank=True) phone_number = PhoneNumberField(blank=True,null=True) def __unicode__(self): return self.event_name html <script> $(function () { // initialize the external events // ----------------------------------------------------------------- $('#external-events .fc-event').each(function () { // store data so the calendar knows to render an event upon drop $(this).data('event', { title: $.trim($(this).text()), // use the element's text as the event title stick: true // maintain when user navigates (see docs on the renderEvent method) }); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); // initialize the calendar // ----------------------------------------------------------------- $('#calendar').fullCalendar({ eventDrop: function (event, dayDelta, minuteDelta) { saveMyData(event); }, eventLimit: true, // for all non-agenda views views: { agenda: { eventLimit: … -
django does't track any change or any new code i make
When I make any changes or write a new code to django project files like urls,views ..etc , Django does not execute these codes and does not give me any errors either ( it is only display and execute the old code that i have changed ) An example of this in my urls if i have a urlpatterns like this :- path('hi', views.HomePageView.as_view(), name='home') and i change it to be like this :- path('bye', views.HomePageView.as_view(), name='home') in the Browser if i write the url " http://127.0.0.1:8000/bye" (the new url) django will give me ( Page not found (404 ) but when i write " http://127.0.0.1:8000/hi" (the old url) it works. and if i add new urlpatterns or new view or any thing django doesn't recognize it. I hope I have clarified my problem correctly I am not very good at English. i use postgresql DB my main urls.py file:- from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls', namespace='core')), ] # informed the location about the media files urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my app urls.py file :- from django.urls import path from . import … -
What would be the best way to run daily automated tests for a web scraper?
I maintain a REST API built with Django REST that, internally, scrapes several webpages to retrieve a bunch of information. I have tests for every endpoint that check whether the scrapers are still working. They actually connect with the pages and check that the sources remain unchanged and that everything is still fine basically. I would like to run these tests several times per day, and be notified when any of these scrapers fail. I'm not sure how should I approach this. I've been looking at CI tools, but I'm not even sure if that's what I want. I'm looking for something that allows me to: 1) Run tests automatically every X hours 2) Notify me of the results What's the best tool for this? -
Datatables has only 10 rows accessible outside the DataTables creation function
I am using Django and in one of my tamplates I use datatables (1.10.19) to display my table data. This is how my code looks like: $(document).ready( function () { table = $('#mytable').DataTable({ "pagingType": "full_numbers", data: dataSet, columns: [ { title: "Naslov zahtjeva" }, { title: "Datum slanja" }, { title: "Status" }, { title: "Rok Izvršenja." }, { title: "Id zahtjeva" }, ], "fnCreatedRow": function(row, data, index){ $(row).addClass("clickable-row"); $(row).attr('data-href', data[4]); $(row).addClass("table_row_point"); }, }); Problem occurs at the line -> $(row).attr('data-href', data[4]); I have a different function that is suposed to use that 'ID' from 'data-href' attribute in order to go to another page like this jQuery(document).ready(function($) { $(".clickable-row").click(function() { window.location = $(this).data("href"); }); }); Thing is it works fine for first 10 rows, and when I try 'console.log( this );' I get Only for the first 10 rows, and it acts like other 3000 don't even exist, I believe it is connected to the default value of 10 rows that appear, but it makes no sense to me for data to be displayed normally, but the 'tr' element not to exist for all, but 10 of them. Note: When I place this function into DataTable creation code (1st snippet) … -
Access dictionary in Django template
I have a property in the Circuit model which calculates for each Diameter the corresponding total pipe length for that diameter. The code is given below: @property def pipe_lengths(self): components = Component.objects.filter(circuit=self) diameters = Diameter.objects.filter(project=self.system.project, material = self.material_type) pipe_dict = {} length = 0 for diameter in diameters: for component in components: if component.diameter == diameter: length += component.length pipe_dict[diameter] = length length = 0 print("PIPE_DICT IS: " + str(pipe_dict)) return pipe_dict This seems to work fine, the output of the print statement seems okay. However now I want to access this dictionary in my template, below is the simplified code I already have: {% extends 'base.html' %} {% block content %} <h2>Circuit name: {{ circuit.circuit_name }} <h3><strong>Piping lengths</strong></h3> <table border="1" style="width:100%"> <tbody> <tr> <td><h3>nominal diameter</h3></td> <td><h3>length [m]</h3></td> </tr> {% for diameter in circuit.pipe_lengths %} <tr> <td><h3>{{ diameter.nom_diameter }}</h3></td> <td><h3>{{ circuit.pipe_lengths[diameter] }}</h3></td> </tr> {% endfor %} </tbody> </table> {% endblock %} I can access the diameter.nom_diameter. However when I try to access the specific length-value by the code: circuit.pipe_lengths[diameter] this does not work. I get the following error: TemplateSyntaxError at /solgeo/28/system/182/circuit/295/ Could not parse the remainder: '[{{diameter' from 'circuit.pipe_lengths[{{diameter' Help is very much appreciated. -
Is there any alternative for django-markdown package?
I want to store textual data in django model with some basic editing functionality. Please suggest some latest django package. -
should I use abstract model in this situation?
I'm wondering what is the best way to represent the models, because there are some fields in common and others that change according to the category. Example: Common fields: (title, author, content, photo, references) Category and its specific fields: Biography (birth data, death data, occupation) Commemorative date (data, description) Music (artist, album, year, musical style) The best would be to create a generic model with common fields and others inherit from it (abstract models)? Create a model for each category, ie repeating the common fields? Create a single model with the common fields and have a category field that when selected would display the category-specific fields in django-admin? In that case, I suppose it would be done with jquery? Any references? There is nothing the material has on this on the internet. Note: All user interaction to register is in django-admin. -
Django How do i pass the url parameter with the form button?
Hi i am Newbie in django i read django documentation but i had made a url with parameteres i want to book a car . for booking i need car id and driver id . after redirect to my booking page . my book now button is not sending the driver id and car id . please help me. for example. i am having a John as a Driver , and he click on Audi To book . after getting his url i want to save it to my booking database . the car Id and driver id . please help me . Sorry for my english . if didnt understand please let me know in comments ill more explain to you and share more content . i am just beginner in field so just learning . Views @csrf_protect def rentacar_car(request, car_id,driver_id): try: args['car'] = Car.objects.get(id__exact=car_id) args['driver_id'] = driver_id except: args['car'] = None args['driver_id'] = None if args['car'] is not None: template = Template.objects.get(template_default__exact=1) return render(request, template_page, args) else: return HttpResponseRedirect('/rentacar/list/') def rentacar_booking(request): if request.POST: template = Template.objects.get(template_default__exact=1) template_page = template.template_alias + str("/rentacar/rentacar_booking_form.html") try: args['car'] = Car.objects.get(id__exact=request.POST.get('car_id')) args['driver'] = Driver.objects.get(id__exact=request.POST.get('driver_id')) except: args['car'] = None args['driver'] = None if args['car'] is … -
Disallow empty string as a valid value on a model with choices that include NULL
I have the following model: class MyModel(models.Model): RED = 'red' BLUE = 'blue' EMPTY_COLOR = None COLORS = ( (EMPTY_COLOR, '---'), (RED, 'red'), (BLUE, 'blue'), ) color = models.CharField(max_length=255, null=True, blank=True, choices=COLORS, default=EMPTY_COLOR) I want the model to validate as valid (using full_clean() on an instance) if the color is set to None (or blue/red, of course) but not when it is set to an empty string. However, the empty string is happily allowed to be defined on the model and is saved in the database even though the choices are defined, in my view, to only ever be NULL, "red", or "blue". Are my assumptions incorrect? How do I go about disallowing an empty string from being a valid value while keeping model validation working when the color is None? -
How to exlude a form field in a django view
I am using Django 1.9.5 I am using a form in my view. I will use same form in forms.py for GET and POST in my view. I want to exclude one field if it is GET. I want it to show all fields if it is POST. I dont want to use 2 different forms in forms.py -
How to change settings variable to be different for every user
MY views.py def change_currency(request): settings.CURRENCY = request.POST['currency'] return HttpResponseRedirect('/') My settings.py CURRENCY = 'EUR' My form <form action="{% url 'change_currency' %}" method="POST"> EUR {% csrf_token %} <input style="display: none" value="EUR" name="currency"> </form> Problem If I manually change the settings.CURRENCY variable in everything works like a charm, but if I make a form and try to change the settings.CURRENCY it doesn't work Problem 2 Will it be possible to have different settings for different users Problem 3 I can't use sessions, beause i use settings.CURRENCY in filters.py and I don't know how to use request.session in filters.py -
Get key, value pair from Django object in template
How do I get key,value pair from object from get_object_or_404 in template, passed from view to template as context? #views.py def detail(request): unknown = get_object_or_404(UnknownModel) return render(request, 'app/display.html', { 'some_data':unknown }) and in app/display.html, I've been trying various approaches: {{ some_data }} {{ some_data.keys }} {{ some_data.items }} {% for key, value in some_data.items %} {{ key }} - {{ value }} {% endfor %}} but none work. If I knew the fields, I can access easily as below, but that's not the case {{ some_data.field_1 }} -
uwsgi cannot process request longer than one minute
I have a Django application that is served within docker container via uwsgi. I have prepared a custom view just to reproduce the issue I'm mentioning. It looks exactly like below: def get(self, request): logger = logging.getLogger('ReleaseReport') logger.critical('Entering and sleeping') time.sleep(180) logger.critical('Awaking') return Response({'response': 'anything'}) The only thing it does (intentionally) is to log message, sleep for 3 minutes, and log another message afterwards. Here is how the log file works after I try to visit the view from Firefox / Chrome / PyCharm's rest API client: spawned uWSGI worker 9 (pid: 14, cores: 1) spawned uWSGI worker 10 (pid: 15, cores: 1) spawned uWSGI http 1 (pid: 16) CRITICAL 2018-08-31 12:10:37,658 views Entering and sleeping CRITICAL 2018-08-31 12:11:37,742 views Entering and sleeping CRITICAL 2018-08-31 12:11:38,687 views Awaking [pid: 10|app: 0|req: 1/1] 10.187.133.2 () {36 vars in 593 bytes} [Fri Aug 31 12:10:37 2018] GET /api/version/ => generated 5156 bytes in 61229 msecs (HTTP/1.1 200) 4 headers in 137 bytes (1 switches on core 0) CRITICAL 2018-08-31 12:12:37,752 views Entering and sleeping CRITICAL 2018-08-31 12:12:38,784 views Awaking [pid: 15|app: 0|req: 1/2] 10.187.133.2 () {36 vars in 593 bytes} [Fri Aug 31 12:11:37 2018] GET /api/version/ => generated 5156 bytes in … -
django.urls.exceptions.NoReverseMatch: Reverse for 'index' not found. 'index' is not a valid view function or pattern name
When I try to access 127.0.0.1:8000/job-slug/ it gives me this error django.urls.exceptions.NoReverseMatch: Reverse for 'index' not found. 'index' is not a valid view function or pattern name. urls.py path('<slug:slug>/', views.DetailJob.as_view(), name='jobdetail'), view.py class DetailJob(DetailView): queryset = Job.objects.all() context_object_name = "job" screenshot of error page link to full error I really don't know how to fix it. Thanks in advance! -
i am unable to understand ,why only delete_node not working
These are three request geeting from user has following, create_node,rename_node are working fine but delete_node request not working. requests: [31/Aug/2018 17:00:53] "GET /buildknowledge/?operation=create_node&id=1&text=New+node HTTP/1.1" 200 16071 [31/Aug/2018 17:01:10] "GET /buildknowledge/?operation=rename_node&id=63&text=pkkkk HTTP/1.1" 200 16071 [31/Aug/2018 17:02:33] "GET /buildknowledge/?operation=delete_node&id=63 HTTP/1.1" 200 16071 views.py: def basetest(request): cu_id = request.user.id if 'operation' in request.GET and "id" in request.GET and "text" in request.GET: operation = request.GET['operation'] pid=request.GET['id'] nodename=request.GET['text'] if "create_node" == operation: p=Buildkb4.objects.create (parent=pid,created_by=cu_id,text=nodename) p.save() elif "delete_node" == operation: Buildkb4.objects.filter(pk=pid).delete() elif "rename_node" == operation: Buildkb4.objects.filter(pk=pid).update(text=nodename) return render(request,"registration/basetest.html") -
How do I structure sensor data in SQL?
I want to store the sensor data from several weather stations on an SQL-database so that it can be viewed through a django web-page. To keep the explanation simple, I read a few sensors (bools and float values) from each weather station every few minutes. I also want to store the time stamp of each reading. What is the best way to structure this data in an SQL database? I would like to keep the system running for years, so it has to be able to store several hundred thousand values. I also need to read these values for display in graphs. -
Django MultiSelectField SelectAll feature
I am using MultiSelectField and would like to add an additional “select all” checkbox. How may I obtain that behavior? models.py from multiselectfield import MultiSelectField class MyModel(models.Model): MY_CHOICES = (. ('a', "A good choice"), ... ('f', "A bad choice"), ) my_field = MultiSelectField(choices=MY_CHOICES, max_length=11) Thanks ahead, Shahar -
Django orm for days difference of current date and a date from db through orm
qs=modelname.objects.all().values(date time.datetime.now(pytz.utc)-'somedatefield') Unsupported operand type(s) for -: 'datetime.datetime' and 'str' I got this this error. I want the difference of two date times in days for the current date time and date time from the db through orm directly. Note: I got the difference in days like this. qs=model name.objects.all().values('somadatefield') I got some date time records like in the image I shown. -
How django authentication actually works?
I really can't understand how Django Authentication Works, I Created Admin Side In my website and i'll make custom authentication model .but when i login django default admin side will also logged in..Please Tell Me How Django authentication exactly works..and read whole documentation of django authentication . I have also Client App How can i diffrentiate both User Login?? -
In Django framework i want to build a Student Registration Form that save data and Assign Roll no
I want to build a system that assign roll no according to class in five digit like if student belong to Matric system auto assign roll no like 10000 and same as increment on next student. And if enter belong to Ninth class assign roll no 09000. My code below is only want roll no logic. Model.py class student(models.Model): name = models.CharField(max_length = 50) city = models.CharField(max_length = 50, blank = True, null = True) roll_no = models.IntegerField(default= 0) degree = models.CharField(max_length =50, blank = True) marks = models.IntegerField(default=0, blank=True, null=True) dat = models.DateTimeField(' Date Published',auto_now=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'students' View.py import requests from django.shortcuts import render from .models import student from .forms import student_form from django.http import HttpResponseRedirect def index(request): obj = student.objects.all().order_by('-dat') if request.method == 'POST': form = student_form(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/studentform/') else: form = student_form() return render(request, 'Students/register.html', {'form':form, 'obj':obj}) Form.py from django.forms import ModelForm, TextInput from .models import student from django import forms class student_form(forms.ModelForm): name = forms.CharField(widget= forms.TextInput, max_length=50) city = forms.CharField(widget= forms.TextInput, max_length=50) degree = forms.CharField(widget= forms.TextInput, max_length=50) marks = forms.CharField(widget= forms.NumberInput, max_length=50) class Meta: model = student fields = ['name','city','degree','marks'] -
Django Rest Framework how to forbid users to change their username?
I'm creating UserSerializer and want to allow users to create new accounts but forbid them to change their usernames. There is a read_only attribute that I can apply but then users won't be able to set a username when creating a new one. But without that It allows me to change it. There is also a required attribute which unfortunately cannot be used with read_only. There is no other relevant attribute. One solution is to create 2 different Serializers one for creating User and another from changing him, but that seems the ugly and wrong thing to do. Do you have any suggestions on how to accomplish that without writing 2 serializers? Thanks for any advice. PS: I'm using python3.6 and django2.1 -
The checkbox on django web page is turned in to checked=true when i post the form
I have Django 1.9.5 web project. I have a page and a form on it. In the form there is a checkbox that is not Cehecked. In the model : delete_student = models.BooleanField(default=False, verbose_name=_("DELETE This Student")) When i save and post this form the page comes back with same form values. But this time the checkbox is checked. I don't want it to be checked without somebody clicks it. The checkbox should remain unchecked unless somebody clicks it.