Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Link a view from django HTMLCalenders
I am using HTMLCalendars in my django admin what I want to do is clicking on button it should take me to that link but its is not working def formatday(self, day, weekday, events): """ Return a day as a table cell. """ # views.create_event('08:30:00', '09:30:00', '2013-12-09') day_date = date.today() events_from_day = events.filter(start__day=day) events_html = "<ul>" for event in events_from_day: events_html += event.get_absolute_url() +"<br>" events_html += "</ul>" + "<select onchange='location = this.value;'><option value=''>new</option><br>" time_slot = TimeSlots.objects.all() for timeset in time_slot: events_html += "<option value='views.create_event('08:30:00', '09:30:00', '2008-12-09')'>" + str(timeset.start) + "</option><br>" events_html += "</select><a href='{% url 'new_event' '08:30:00' '09:30:00' '2018-12-09' %}'>click</a>" if day == 0: return '<td class="noday">&nbsp;</td>' # day outside month else: return '<td class="%s">%d%s</td>' % (self.cssclasses[weekday], day, events_html) -
When adding an object i need the user to be taken authomaticaly
I need when saving an object on the DB to be inserted authomaticaly the user of the peer. I need this, just because if i let the models as they were with Foreign key, basically the user could change it;s user so when saving the object we could have different users etc. Therefore i changed in my models from user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True, null=True, default=1, on_delete=True) to user = models.CharField(blank=True, null=True) and put these lines: def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) if not obj: user = request.user form.base_fields['user'].initial = user.user form.base_fields['email'].initial = user.email return form AttributeError at /admin/parcare/parking/add/ 'User' object has no attribute 'user' What am I doing wrong? -
What do I need to_url method in path converter? Django
What do I need to_url method in path converter? Django. I can find only few exaples on official docs and can't understand the use of this method. What does to_url exaclty do? class FourDigitYearConverter: regex = '[0-9]{4}' def to_python(self, value): return int(value) def to_url(self, value): return '%04d' % value -
Selenium Grid in Python - functional tests timeout after first test everytime
So I have been trying to write functional tests for my django application, and I appear to be having some strange behaviour: every single time I run my tests, Selenium hangs indefinitely after the first test, only when I reboot the hub and node containers does it let me run another test, after which it hangs forever again. I have studied this thread as at first glance it appears to be the same error, but even with those changes I have the same problem. Description of my setup: I am using docker-compose, with 3 (main) services: django, selenium_hub, and selenium_firefox. Find my docker-compose.yml below: version: '3' services: web: build: context: django dockerfile: Dockerfile stdin_open: true tty: true volumes: - ./django/my_web:/src/my_web/ ports: - "8000:8000" networks: ["my-net"] nginx: image: nginx volumes: - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro - ./nginx/static:/usr/share/nginx/djangodocker/static - ./nginx/certs/:/etc/nginx/conf.d/certs:ro ports: - "80:80" - "443:443" depends_on: - web networks: ["my-net"] selenium_hub: container_name: selenium_hub image: selenium/hub volumes: - /dev/shm:/dev/shm environment: - DBUS_SESSION_BUS_ADDRESS=/dev/null shm_size: 512MB ports: - "4444:4444" networks: ["my-net"] selenium_firefox: container_name: selenium_firefox image: selenium/node-firefox-debug volumes: - /dev/shm:/dev/shm shm_size: 512MB environment: - DBUS_SESSION_BUS_ADDRESS=/dev/null - HUB_PORT_4444_TCP_ADDR=selenium_hub - HUB_PORT_4444_TCP_PORT=4444 ports: - "5901:5900" depends_on: - selenium_hub networks: ["my-net"] networks: my-net: As you can see I've tried mounting /dev/shm, setting shm_size … -
How to avoid duplicate object creation
I have duplication problem now I don't know the way forward need help I have this model branch with a reverse relation to stock class Branch(models.Model): name = models.CharField( 'Branch', unique=True, max_length=10, validators=[MinLengthValidator(5)]) location = models.TextField(max_length=650, blank=True, help_text='location of the linsan branch') class Meta: verbose_name_plural = 'Branch' def __str__(self): return self.name class Stock(models.Model): branch = models.ForeignKey( Branch, related_name = 'branch', help_text='Enter the name of the branch', on_delete=models.CASCADE, blank=False, null=False ) manufacturers_name = models.CharField( max_length=50, blank=True) description = models.CharField( max_length=50, help_text='Enter the name of the product here', unique=True ) model_number = models.CharField( max_length=25, blank=True, null=True, help_text='Enter the model number of the item if any') color = models.CharField( max_length=20, default='black', blank=True, null=True,) quantity = models.PositiveIntegerField( validators=[validate], verbose_name='Quantity In stock') retail_price = MoneyField( max_digits=14, decimal_places=2, default_currency='NGN', blank=False, verbose_name="Retail Price") customer_price = MoneyField( max_digits=14, decimal_places=2, default_currency='NGN', blank=False) added = models.DateTimeField( auto_now_add=True, help_text='The date the product was added') image = models.ImageField( blank=True, null=True, upload_to='uploads/%Y/%m/%d/', help_text='Upload the image of the product if any') history = HistoricalRecords() class Meta: ordering = ['description'] def __str__(self): return self.description And another model with a foreignKey to stock class WaybillItem(models.Model): waybill = models.ForeignKey(Waybill, on_delete=models.CASCADE, related_name='waybill_item') product = models.ForeignKey( 'stock.Stock', on_delete=models.CASCADE, blank=False, null=False) quantity = models.PositiveIntegerField(validators=[validate, MinValueValidator(1)]) In my stock app I … -
Request current users API token Django REST Framework
I have a django webapp that is using the django REST framework to generate various API endpoints. I am able to ensure only logged in users can view/read these endpoints, but now I am at the stage of development where I want users to post to the API using tokens. I have successfully done this, however I have hard-coded the users token into the post request in Javscript... This worked for testing, but obviously is not a good final solution. Is it possible to request the current users token somehow? I could then include this token in the POST request head automatically? Thanks for any help/feedback in advance!! -
Virtualhost on SSL - Can't run Django app in virtualenv after upgrading from httpd 2.2 to 2.4
I need help in understanding if I have correctly upgraded my website's older config from httpd-2.2 to httpd-2.4. It was hosted on a local server that we have since retired and the entire /etc/httpd and /var/www directories were copied to an EC2 instance with MySQL installed on the instance itself. The Django-1.5 app (yes it needs to be upgraded) runs on the mod_wsgi module in daemon mode. I have upgraded the Apache modules and now when I run python manage.py runserver after activating my virtualenv environment and it gives no errors. But when I navigate to my EC2 public IP address with https, it keeps loading the page and times out afterwards. At the moment the httpd.conf redirects any port 80 requests to the website domain address, but I'd like to test the deployment on EC2 using bare IP address first before we can update our DNS records. Another thing I did was to add the public IP address of my EC2 machine to the ALLOWED_HOSTS list, along with both localhost and 127.0.0.1. Possible SELINUX problem tried but didn't work The output of running httpd after runserver gave the following output: (13)Permission denied: AH00072: make_sock: could not bind to address … -
Search in two models
I'm trying to get the exact code to look at two different models with a single button, but I can not find the form. I'm working with Django 2.5 and python 3.6. I have the following code. #models.py from django.db import models class Estadoadm(models.Model): estadm = models.CharField(max_length=45, unique=True) descripcion = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.estadm class Estadofis(models.Model): estfis = models.CharField(max_length=45, unique=True) descripcion = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.estfis In the view I am showing a code that allows me to search in a single model and would like to do the same with the two models. #views.py class GestionarEstados(generic.ListView): context_object_name = 'estados' template_name = 'estados/gestionar_estados.html' success_url = reverse_lazy('gestionar_estados') queryset = Estadoadm.objects.all() def get_context_data(self, **kwargs): context = super(GestionarEstados, self).get_context_data(**kwargs) context['estadofis_list'] = Estadofis.objects.all() return context def get_queryset(self): queryset = Estadoadm.objects.filter() query = self.request.GET.get('query') if query: queryset = queryset.filter(Q(estadm__icontains=query) | Q(descripcion__icontains=query)) return queryset In this template I call the search by means of the variable "query" in the button. #gestionar_estados.html <form method="GET" action="{% url 'gestionar_estados' %}"> <div class="input-group"> <div class="input-group-prepend"> <button class="btn btn-primary" type="submit" id="button-addon1" value="Search"> <i class="fas fa-search"></i></button> </div> <input class="form-control border border-primary" type="text" name="query" placeholder="Buscar por palabra clave" value="{{ request.GET.query }}"> </div> </form> I have tried to … -
Django - how to fix ModelForm CharField doest appear in template page?
I have a ModelForm where one of the fields is set like this: `group_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'float-none', 'pattern':'^[a-zA-Z\d-_]*$', 'style':'width:140px;'}), required=False)` Now when I started the server in development environment, everything works, and the input field appears as it should in the template page. After pushed the code to production environment, and starting the server, this field doesn't appear at all in the template page, though I do see it in the code where it should appear. What can be causing this to happen? Thanks in advance. -
Why does a Django query that looks for an object with a specific id is slower on a large DB than on a smaller one?
Why does a query like this: MyModel.objects.get(id=1) run slower, even by a little bit, on a very large DB table than on a small DB table?. (e.g 10 row table vs 1 million row table) Is it clearly SQL related or is it caused by the software that handles the query (in this case, Django)? -
Python3.6 - cannot import name '_imaging' [Django 2.1.2, Apache 2, CentOS 7]
I'm running my Django application with Apache on CentOS. I already (pip) installed Pillow on my virtualenv(python3.6). When I run python in shell, import PIL._imaging doesn't generate any error. However, When I put this line of code inside the Django application, it generates an error: cannot import name '_imaging'. This is confusing. I set the python path: /var/www/ProjectName/virtualenv/bin/python3.6/site-packages, and the error occurred in the same location, so I think it's not an issue that Django running on another python version. Maybe is a mod_wsgi error? I installed mod_wsgi with yum install python35u-mod_wsgi Can anyone help me with this issue? Thanks a lot. -
Django: How can i do annotate just when all my models have some value
Let me explain better... i have this models: class BetGroup(models.Model): ... expected_value = models.DecimalField(_('Expected Value')... code = models.CharField(_('Code'), max_length=126, blank=True, null=True) ... class Bet(models.Model): ... bet_group = models.ForeignKey( BetGroup, verbose_name=_('Bet group'), related_name='bet', on_delete=models.CASCADE ) is_correct = models.NullBooleanField(_('Is correct?'), default=None) ... i want to make a query when all bets in bet_group is correct sum expected_value. i want to test if all bets are correct then sum expected_value for each bet_group. -
Django Save function doesn't save ID
So i have a saving function, but it doesn't save the id of the object. When i see the message there is a NONE saved. What should i do to have that? The issue is here==> when you click on the new object there is displayed this message: Parking with ID "None" doesn't exist. Perhaps it was deleted? But it is there into the DB. The parking "None | P5 | 2018-10-18 | 2018-10-18" was added successfully. def save(self): list = [] d = self.parking_on while d <= self.parking_off: list.append( Parking(id=self.id, user=self.user, email=self.email, parking_on=d, parking_off=d, location=self.location, numar_masina=self.numar_masina ) ) d = d + timedelta(days=1) Parking.objects.bulk_create(list) class Parking(models.Model): PARKING_PLOT = ( ('P1', 'Parking #1'),('P2', 'Parking #2'), ('P3', 'Parking #3'), ('P4', 'Parking #4'),('P5', 'Parking #5'), ('P6', 'Parking #6'), ('P7', 'Parking #7'),('P8', 'Parking #8'), ('P9', 'Parking #9'), ('P10', 'Parking #10'),('P11', 'Parking #11'), ('P12', 'Parking #12'), ('P13', 'Parking #13'),('P14', 'Parking #14'), ('P15', 'Parking #15') ) user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True, null=True, default=1, on_delete=True) email = models.EmailField(blank=True, null=True) parking_on = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True,help_text='Please select the date you want to come in the office.',) parking_off = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True,help_text='Please select the date when you leave') numar_masina = models.CharField(max_length=8, default="IF77WXV", blank=True, null=True,help_text='Please insert your license plate number') … -
Best practice to have scalable architecture with Angular as frontend and Django as Backend
I have my tech stack Django , Gunicorn with Nginx. I have frontend developed in Angular. I have hosted backend (Django + Gunicorn + Nginx) on AWS , now I want to serve frontend app (angular) I have two option Run frontend and backend on same server Run frontend on different server and backend on different server, frontend will communicate through REST api in above two scenario. Now my question is which method should I follow , what is best practice if I need to scale it to millions of user. If I am going with second option then how I can scale using Elastic Load Balancer since frontend and backend are on different server. Please suggest. -
ImportError: No module named 'nested inline'
I´m using python 3.5.1 and django 2.0.1. I have a django app which I want to start but i get the following error message: ImportError: No module named 'nested_inline' Under settings.py I have in installed apps: INSTALLED_APPS = [ 'nested_inline', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'betonermüdung' ] So.. I can´t understand where the problem could be... can anyone help?? Thank you in advance -
Django annotation count returns wrong number
I have 3 models. When I'm trying to get projects screens count it always return screen count multiplied on members count. Here is the code sample projects = Project.objects.annotate(number_of_screens=Count('projectscreen')).filter( Q(user=request.user) | Q(members__projectmember__user__exact=request.user, members__projectmember__is_active=True) ) class Project(TimeStampedModel): STATUS_PAID = "paid" STATUS_PENDING = "pending" STATUS_CHOICES = ( (STATUS_PAID, "Paid"), (STATUS_PENDING, "Pending"), ) name = models.CharField(max_length=250) preview = models.CharField(max_length=16, default=secrets.token_urlsafe(16)) status = models.CharField(choices=STATUS_CHOICES, default=STATUS_PENDING, max_length=20) user = models.ForeignKey(User, related_name="user", on_delete=models.CASCADE) members = models.ManyToManyField(User, related_name="members", through="ProjectMember") class ProjectMember(TimeStampedModel): project = models.ForeignKey(Project, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) is_active = models.BooleanField(default=False) class ProjectScreen(TimeStampedModel): image = models.ImageField(upload_to=utils.get_file_path, blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) -
Extract date from django query
I have a query with the date filter. queryset=Model.objects.filter(order_created_on__gte='2018-10-10') It constructs a query like this - "Model"."order_created_on" >= 2018-10-10 00:00:00+05:30 Which gives an error for that '00:00:00+05:30' when I qun the query. The queryset populates the data properly, but I want it to run via query. An alternative is to use 'order_created_on__date__gte' but its giving an error, thinkso date filter is not available with __gte. Another alternative is to construct my filters such - 'order_created_on__range=['2018-10-10 00:00:00+05:30']'. Any other alternative available? -
Heroku Django App with Django SQL Explorer not doing queries on Postgress DB
Have deployed a djang site on heroku. I have installed django-sql-explorer on the site. All is fine on local, but on development, because the db is postgress, when running the queries i got error: SELECT * FROM parcare_parking WHERE parking_on = date('now','+1 day'); The error is: function date(unknown, unknown) does not exist LINE 3: WHERE parking_on = date('now','+1 day'); ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. SELECT * FROM parcare_parking WHERE parking_on = "2018-10-08" fired column "2018-10-08" does not exist LINE 1: SELECT * FROM parcare_parking WHERE parking_on = "2018-10-08... ^ However SELECT * FROM parcare_parking fired correct resuls. They were on my local dev, but somehow from my local SQLite3 to Postgress's Heroku is an incompatibility. What should i do? Thank you! -
Passing time as argument in django url
in my view I have an argument of time to be passed but how do i pass it through a django url my view is def create_event(check): TimeSlots.objects.create(start=check) return HttpResponseRedirect("index.html") and i tried a url url(r'^new/(?P<time>\d{2}:\d{2}:\d{2})/$', views.create_event, name='check'), I called it as <a href="{% url 'check' 08:30:00 %}">click</a> but it doesnt work and gives error Could not parse the remainder: ':30:00' from '08:30:00' -
Why does apache keep changing my host name?
So I have a Django application server all set up using Apache and uWSGI and a proxy system. One small problem...Something keeps changing my hostname!!! It almost resembles a rewrite rule but I searched my httpd.conf and couldn't find any that fits the bill. Whenever I send an HTTP URL: http://www.example.com/polls Django receives this url from the proxy: http://www.example.com/kpolls It's really annoying! something keeps adding that damn k to my hostname and I have no idea what! Please help! Some extra info: So my proxy so far is pretty simple: ProxyPass "/" "uwsgi://127.0.0.1:49152/var/run/app_name.sock" ProxyPassReverse "/" "uwsgi://127.0.0.1:49152/var/run/app_name.sock" (tried localhost and www.example.com just to be sure. no effect so hostname is resolving correctly.) Seems to me that the proxy is altering it before handing the request off to Django? -
loadfixtures vs loaddata in manage.py
I'm new to django and working on a modern django/Wagtail CMS app that is seeded using the command python manage.py loadfixtures. It seems like loaddata is the more common command, and I'm finding it incredibly difficult to find any documentation on loadfixtures at all. Could anyone point me towards the difference? It appears under the [Core] section of "available subcommands." As an aside, I'm essentially trying to dump and seed some static page data for the site. -
Problems on using DateTimeField in Django and SQL Server
I have a very simple form in Django where the user needs to enter date and time values. So, this is what I have setup so far. models.py date_time_restore = models.DateTimeField(verbose_name='Date & Time restore') forms.py date_time_restore = forms.DateTimeField(initial=datetime.datetime.now(),widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) restore.html <tr> <td>Restore Date & Time *</td> <td>{{form.date_time_restore}}</td> </tr> When this is rendered, I get this screen below. Saving it gives me an error and this is what I have in the POST. Logging the form content in my errorlog, I get this: Enter a valid date/time. Does anyone have any idea on how to handle that? In SQL Server, the data type is datetime2(7). Thanks, Marcos Freccia -
Django: Building a safe validator of GET request parameters
I am trying to figure out how to validate following type of url parameters: def get(self, request, id_of_the_record): due to the fact, that it is not available in the request.GET dictionary, it is impossible to build a form with id_of_the_record in it. I have came up with an idea of creating a custom dicitonary like this: try: self.request_get_dict = dict() self.request_get_dict['id_of_the_record'] = id_of_the_record except Exception as e: raise Exception() and once it is done, I am checking it wil the following form: form_extra_parameter = TestForm(self.request_get_dict) if form_extra_parameter.is_valid(): forms.py: class TestForm(forms.Form): id_of_the_record = forms.IntegerField(validators=[MinValueValidator(0)], required=True) Is there a better way of validating it? -
update a field from default user model django
I am making an app that wants the default user model to be extended. I want to customize some of the fields, like adding some restrictions to the username. For example, the username must be between 4 to 16 characters and may contain lowercase alphabets, dashes and dots only. My question is that how to update these fields in django? What is the best practice to do it. My model is below. from django.db import models from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): objects = CustomUserManager() followers = models.ManyToManyField("self", related_name="following", symmetrical=False) -
Django debugging: how to pretty print an object in template
In Django i want to know how to see the full objects which may have nested objects like model, formset etc in template as html or <pre> element Is it possible. Because it will help me to debug and check the results.