Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display Django Field properties, such as min_value and max_value, in the Template
I have a Django Form with an IntegerField. I give the IntegerField a min_value and a max_value. I would like to DISPLAY that min_value and max_value for the user, so I'm trying to include it in the template next to the input field itself. Seems like this should not be so hard, but it isn't working. :-( Below, the "print" statement in views.py works just fine. So I know that one can access the min_value from the field with just ".min_value". But the min_value in the template does not show up in the browser. Thoughts anyone?? In forms.py class MyForm(forms.Form): somenumber = forms.IntegerField(min_value=0, max_value=12) In views.py: form = forms.MyForm() print(form.fields['somenumber'].min_value) ... context = {'form':form} ... In template: {{ form.somenumber.min_value }} -
Django test pagination EmptyPage
I am trying to write a function that tests if we exceed the page limit it returns the last page, but I'm a little stuck Here is my function: def test_pagination_returns_last_page_if_page_out_of_range(self): response = self.client.get(reverse('catalog:search'), {'query': '', 'page': 999}) # Check that if page is out of range (e.g. 999), deliver last page of results self.assertEquals(response.context['products'], response.context['products'].paginator.page(2)) When I run this test it returns to me: Traceback (most recent call last): File "/home/rouizi/pur_beurre/catalog/tests/test_views.py", line 120, in test_pagination_returns_last_page_if_page_out_of_range self.assertEquals(response.context['products'],response.context['products'].paginator.page(2)) AssertionError: <Page 2 of 2> != <Page 2 of 2> my view function is somthing like this: ... try: prods = paginator.page(page) except EmptyPage: # We return the last page prods = paginator.page(paginator.num_pages) return render(request, 'catalog/search.html', {'products': prods, 'query': query}) -
where Environment variables for python are saved
I know to set an environment variable in python is to use os.environ['API_USER'] but where this variable is saved, I supposed this environment variable is saved in .env file but it wasn't. on the console to retrieve all the environment variables use command: os.environ but don't know where are saved. need your help, Thanks! -
How to render a name after clicking/tabbing out of a field in Django?
I have a form that is used to keep track of when employees enter/leave an area to track times. The first field is where they enter their employee #. I have a table in my database that comes from another model, called Salesman, where all the employee data (names, dept., etc.) is stored, as shown here (only fields relevant to question shown): alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) ... def __str__(self): return "" My model for the form is set so that the employee_number field is related to Salesman, so that the numbers entered in my form can only be numbers that are valid in Salesman based on the id and so that I can filter "who" can submit the form or not (depending on team/status). models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) ... forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def clean_employee_number(self): employee_number = self.cleaned_data.get('employee_number') if employee_number is None: raise forms.ValidationError("Must enter emp #") elif employee_number.team not in ('WF', 'WP', 'OM') or employee_number.employee_status not in 'A': raise forms.ValidationError("Employee not valid, please contact manager") return employee_number … -
Django: Way to Get List of All Running Commands?
If I run htop, I see a list of all running processes, and the commands that spawned them. Is there a way to get the list of running commands from inside Django? I looked at the docs for the OS module, but didn't yet spot a way to do it. -
Django Admin: Custom ordering according to concatenated charfields of a related manytomany model
Here are my simplified models: class MasterFood(models.Model): class Meta: verbose_name_plural = 'Master Foods' FOOD_TYPE_CHOICES = ( ('F', 'Fats'), ('C', 'Carbohydrates'), ('P', 'Proteins'), ('O', 'Others'), ) food_name = models.CharField(max_length=255) food_type = models.CharField(max_length=20,choices=FOOD_TYPE_CHOICES) def __str__(self): return self.food_name class MasterMeal(models.Model): class Meta: verbose_name_plural = 'Master Meal Plan Meals' proteins = models.ManyToManyField(to="MasterFood", limit_choices_to={'food_type': 'P'},blank=True,related_name='food_proteins') carbohydrates = models.ManyToManyField(to="MasterFood", limit_choices_to={'food_type': 'C'}, blank=True, related_name='food_carbohydrates') fats = models.ManyToManyField(to="MasterFood", limit_choices_to={'food_type': 'F'}, blank=True, related_name='food_fats') def all_foods(self): return list(self.proteins.all())+list(self.carbohydrates.all())+list(self.fats.all()) def __str__(self): return ', '.join(map(lambda x: x.food_name, self.all_foods()))+f' ({len(self.all_foods())})' and my modelAdmin object in admin.py: class MealAdmin(admin.ModelAdmin): model = MasterMeal save_as = True ordering = ('proteins__food_name','carbohydrates__food_name','fats__food_name',) What I would like is in the Django admin page for MasterMeals is to have each object named after the __str__ method given in my MasterMeal model, but in a different ordering than the default. Specifically, I would like the objects to be sorted in alphabetical order according to the __str__ method definition, and if possible, I don't want to modify my MasterMeal model to add another field to achieve this. I have tried several things such as the ordering = ('proteins__food_name','carbohydrates__food_name','fats__food_name',) in my MealAdmin object as well as ordering = ('proteins','carbohydrates','fats',). I have also tried overwriting the queryset of the ModelAdmin with an annotate function … -
How to update the field of django model from the existing field values of object
How to update the field of django model by taking/extracting values or filtering values from existing field of same object? I have the following model: from django.contrib.postgres.fields import JSONField,ArrayField class MyUrlModel(models.Model): urls_json_data = JSONField(blank=True,null=True,default=dict) urls_list = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) field urls_json_data has the following data in json: [{"protocol":"http","hostname":"google.com","port":80"},{"protocol":"https","hostname":"apple.com","port":443"}] Here, i would like to fetch the structures from urls_json_data and make it into url structure like following and save them under urls_list which is ArrayField. urls_list=['http://google.com:80','https://apple.com:443'] So whenever urls_json_data get's updated, I want to fetch the URLs from it and save it under urls_list on the fly. What is the best approach to do it, is it by signals or by altering save method? urls_list = [] for each_data in urls_json_data: url = each_data['protocol']+each_data['hostname']+each_data['port'] urls_list.append(url) -
How can I change in db values of model object by celery worker with redis in Django?
I want to create an app with workers which in the background changes the value of Simulation model. Firstly user clicks to start simulation, wait some time, click to end simulation, and then on the page shows a value difference (from the start to the end of simulation) which was changed by the background worker. The main problem that I just can't reach the worker's task. I can reach @receiver after Simulation model saved and correctly check model`s values but I cant change model values in db by workers. The project called app, application - myapp. app/myapp/models.py from django.db import models class Simulation(models.Model): # changed every simul day created_date = models.DateField(auto_now_add=True) today = models.DateField(auto_now=False, auto_now_add=False) status = models.BooleanField(default=False) daemon_active = models.BooleanField(default=False) info = models.TextField() def get_simulation_day(self): """days passed after simulation firstly start""" # sim = Simulation.objects.all().last() return (self.today - self.created_date).days app/myapp/views.py def simulate(request, action): sim = get_simulation() if action == "disable" and sim.status == True: sim.status = False sim.save() elif action == "enable" and sim.status == False: print('view simulate ok') sim.status = True sim.save() print('view simulate ok after save') context = { "simulations_exists": True, "days_passed": sim.get_simulation_day(), "simulation_today_str": (sim.today).strftime("%d %B, %Y"), "simulation_status": sim.status } return render(request, "simulation_page.html", context=context) app/myapp/tasks.py import logging … -
How do you test django-axes with a Django unit test?
I'm using Django Axes with my Django project to ensure that if someone is trying to guess a password, their IP gets blocked for a while. It's setup, and works great. I want to write a Django test that makes sure that after X number of guesses, the user is really locked out. The problem I'm having is that if you try to use the django test client to do a login as you normally would: self.client.login(username="invalid_user", password="invalid_password") Axes crashes, because it isn't getting a request arg: Traceback (most recent call last): File "/opt/my_project/website/login_app/tests/test_views.py", line 71, in test_brute_force_attempts self.client.login(username="invalid_user", password="invalid_password") File "/opt/my_project/venv3/lib/python3.6/site-packages/django/test/client.py", line 602, in login user = authenticate(**credentials) File "/opt/my_project/venv3/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 73, in authenticate user = backend.authenticate(request, **credentials) File "/opt/my_project/venv3/lib/python3.6/site-packages/axes/helpers.py", line 411, in inner return func(*args, **kwargs) File "/opt/my_project/venv3/lib/python3.6/site-packages/axes/backends.py", line 39, in authenticate "AxesBackend requires a request as an argument to authenticate" axes.exceptions.AxesBackendRequestParameterRequired: AxesBackend requires a request as an argument to authenticate This is a known issue, and is discussed here: https://github.com/jazzband/django-axes/issues/433 As far as I can tell, you just need to pass self.client.login a request= arg, which it will pass to django.contrib.auth.authenticate, and it'll be happy. I can't figure out where to get this request within a test … -
Can I make a select type="file"?
Ok, So I need to implement a drop-down where I can choose some file from a folder directory. I already have the dropdown displaying the files but when I'm making the query I'm getting this error django.utils.datastructures.MultiValueDictKeyError:'xxxxxx' I'm not sure if is even passing the whole file or just the name of the file. Can I do something as a <select type="file">? or can I connect an hidden input type="file" to the select? Thanks -
Intermittent hang using pandas read_parquet inside django api wsgi thread
I'm writing an API using Django 2.2, djangorestframework 3.9, and pandas 0.25. I use AWS Elastic Beanstalk to deploy under Amazon linux 2.8 using python 3.6. The application uses pandas DataFrame objects stored as .parquet files in an s3 bucket. In the python shell I can call my custom properties, for example data_file.row_count should read in the parquet file as a pandas DataFrame (using pandas.read_parquet('s3://bucket-name/file-name')), and simply return the number of rows in the file. This has always worked without issue via the python shell, both locally and remotely. The problem happens when that read_parquet method runs as a result of a web request on the ec2 instance via wsgi. I want the application to simply respond to a web request with the row_count of a particular data_file. Right now, it only works about half the time, and the other half it hangs for about 5 minutes and gives me a generic 500 error with no stacktrace (Yes DEBUG==True). I tried a workaround where I downloaded the s3 file to a tmp local file, then ran pandas.read_parquet('TMP_FILE.parquet'), and the hang happened on the read_parquet not on the s3 download, so I ruled out any network issues between my ec2 instance … -
In Django models, can I fetch the value of a field, process it and store it in another field?
I want to reference the value of a field in another field. I've tried default=self.key_name * 2, but that won't work. class Pizza_size(models.Model): length = models.DecimalField(decimal_places=2, default=0) price = models.DecimalField(decimal_places=2, default=self.length*2) When I create an object with the Pizza_size class, if the value of length is 5, I want the value of price to be 10 by just running the command Pizza_size(length=5). -
How can I organize a database with products and users?
I am currently trying to organize a django database model for an online shop-system with users and products. My code: class UserData(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=500) bought_products = models.ForeignKey(MarketProducts, on_delete=models.CASCADE) class VendorData(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=500) sold_products = models.ForeignKey(MarketProducts, on_delete=models.CASCADE) class MarketProducts(models.Model): category = models.CharField(max_length=100) vendor = models.ForeignKey(VendorData, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.CharField(max_length=1000) price = models.IntegerField() pub_date = models.DateTimeField('Date published') image = models.ImageField(upload_to=b'shop/media/images/') likes = models.IntegerField() dislikes = models.IntegerField() How can I organize a good working system so all the products a user bought are saved inside the bought_products column and all the products a vendor sold can be saved inside the sold_products column. Do I have to use a ForeignKey for that or is there something more suitable for this situation? Also, if there is anything unwise about the existing structure of the database model (for example the current image field column only saves the link but not the image itself which is kinda weird...), please feel free to correct me :). Many thanks in advance :D -
How to use HTTP headers to track number of subscribers?
I am trying to implement a web based feed reader using Django by implementing the package django-feed-reader (https://pypi.org/project/django-feed-reader/). But in the project description the author mentioned like this: Tracking subscribers and read/unread state of feeds The app does not (currently) track the read/unread state of posts within a feed. That will need doing in your project according to your needs. The app assumes that each feed only has one subscriber that is the project itself. If your project can allow personal subscriptions for individual users, you can let the app know on per feed basis how many subscribers it has by settings num_subs on a Source object. The app will then report this via the user agent to the feed source for analytics purposes. I have no clue what does the last lines means and how to implement the same. Please help me resolve this. (My application need to avail authenticated users to subscribe feeds they wanted.) The structure of the 'Source' model is as follows: class Source(models.Model): # This is an actual feed that we poll name = models.CharField(max_length=255, blank=True, null=True) site_url = models.CharField(max_length=255, blank=True, null=True) feed_url = models.CharField(max_length=255) image_url = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(null=True, blank=True) last_polled … -
Why are my ValidationErrors not rendering anymore?
I have a form that has to check a few things before submission to make sure the data is valid. Before I did a few changes (went from class based views to function based) everything worked fine, but when I went back to test everything I noticed that a very important part was not working properly, which is the number validation. What used to happen before was that, if a number that was not in the DB was entered, the user would be shown an error at the top. If they entered a number that was in the DB, but it was not the right "team" then it would show an error. I was handling this in forms.py, and completely forgot about this since it was working before, and all the things I started working with were in views.py. Now, while it will not actually submit the form (so it is still going through the logic) it will not display any errors. It will just re-render the page but empty, and not submit anything unless the data entered is right. The logic that would handle this was clean_employee_number. I'm not sure If I deleted something from my html without noticing, … -
Inline display many to many admin django
Simplified example of my code would be: in models.py: from django.db import models class A(models.Model): ... class C(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): a_fields = models.ManyToManyField(A) then in admin.py @admin.register(A) class AAdmin(admin.ModelAdmin): pass class CInline(admin.TabularInline): model = C extra = 0 @admin.register(B) class BAdmin(admin.ModelAdmin): inlines = (CInline,) It won't show fields of A inline when I open the add new form for B entity. It actually shows a drop box with pre-existing entries and allows me to click on '+' to add new A, which is not desired behavior plus the same happens without using inline in the first place. Thanks in advance! -
Added additional model to models.py, but I get `OperationalError: no such table`
My webapp webapp has two tables already registered in models.py. Let's call them Model1 and Model2. They're built, they work, they're both registered in my webapp's admin.py and the entire webapp is running. I can go to the admin console (/admin) and see that both the tables are there, and I can look through them. I wanted to add a third table, Model3. I wrote out the code in models.py - it looks very similar to the other two models, with slightly different fields. I modified admin.py to include it, like the other two. I then deleted the migrations folder and I did the following Django commands: $ python manage.py makemigrations webapp Migrations for 'webapp': webapp/migrations/0001_initial.py - Create model Model1 - Create model Model3 - Create model Model2 $ python manage.py migrate webapp Operations to perform: Apply all migrations: admin, webapp, auth, contenttypes, sessions Running migrations: Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK I'm not sure what those migrations are that are actually getting run (I haven't changed Model1 and Model2 recently). When I run the webapp and enter the admin console, Model3 appears along with Model1 and Model2, but clicking on it yields the following error: Internal Server Error: /admin/webapp/model3/ … -
It is safe to use Django urls to run code?
I'm worried about the security of my web app, I'm using Django and sometimes I use AJAX to call a Django url that will execute code and then return an HttpResponse with a message according the result, the user never notice this as it's happening in background. However, if the url I'm calling with AJAX is, for example, "runcode/", and the user somehow track this and try to send a request to my domain with that url (something like "www.example.com/runcode/"), it will actually run the code and I feel like it is a security hole. Should I use Django urls to run code with AJAX?, if this is ok how I can avoid the users to notice that the URL exists? -
Social-Auth-App-Django vs. Django-Allauth
I need to add (optional) social authentication to a Django project with multiple user types and groups. After searching, I came across the libraries Social-Auth-App-Django, and Django-Allauth for handling social login. Which of these libraries should we choose in 2019? Security is the top priority for me. Thanks in advance, -
Checking if input from a form is in table django
The goal is to take in input from a user and see if that input matches information in a table in a database. If there is a match, delete that information from the table. If there isn't a match, clear out the form and say that there isn't a match. Here is the views file. from django.shortcuts import render, redirect from django.contrib import messages from .forms import CheckoutForm, CheckoutRegForm from .models import Checkout from books.models import Addbook def checkout(request): if request.method == 'POST': form = CheckoutForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'The book has been checked out.') return redirect('front-page') else: form = CheckoutForm() return render(request, 'checkout/checkout.html', {'form': form}) def checkin(request): if request.method == 'POST': form = CheckoutRegForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] member_id = form.cleaned_data['member_id'] if title in Checkout.objects.all(): Checkout.objects.filter(title = title).delete() messages.success(request, f'The book has been checked in.') return redirect('front-page') else: messages.error(request, f'Error: This book is not in the Checkout table.') return redirect('checkin') else: form = CheckoutRegForm() return render(request, 'checkout/checkin.html', {'form': form}) From my understanding, forms in Django collect user information and store it in a dictionary 'form.cleaned_data'. I tired multiple ways to set up that if statement to see if there is a match with the input from the … -
How to install libpq-fe.h?
I cannot figure this out for the life of me. When I pip install django-tenant-schemas it tries to install the dependency psycopg2 which requires the Python headers and gcc. I have all this installed and still keep getting this error! ./psycopg/psycopg.h:35:10: fatal error: libpq-fe.h: No such file or directory So to install libpq-fe-h I need to sudo apt-get install libpq-dev.. ..which returns.. libpq-dev is already the newest version (10.10-0ubuntu0.18.04.1). Then when I sudo find / libpq-fe.h it doesn't seem to be in my OS. I am lost at this point. If anyone can help I would highly appreciate it. -
What seems to be the problem with template tags?
Why doesn't this template tag work when I run server and on the browser doesnt show me anything when I add in the url static/images/django.jpg ? Hello I am a newbie here, on the path to full-stack development. While learning about Django-Static Files through python and django fullstack web development and after creating templates and template tags, I was not able to inject an image to an html file because as indicated in VS Code in red color the text and quotaition marks. images/Django.jpg" %} " As I see it must be a problem with code formater/code runner or that settings in VS code about single/double quotation marks, but still this is the first problem I encountered and I think I would have encountered it before if it was extension problem ? Here are images: problem 1 -
How to create xml sitemap of all the Django project detail page urls
I'm trying to get all the urls for specific Django project detail pages for instance: path('/mysite/speical/<pk>',views.DetalView.as_view(),name='detail') /mysite/special/1390u20 /mysite/special/930nfdn /mysite/special/29093nn How do I print all these urls into an xml file in the shell? I'm not sure where to even start. -
AttributeError at /pre_pred/
I've installed all the requirements and successful in running the local server but when I tried to run the prediction part of this 4th_umpire(The cricket match predictor using Random Forest algo project I'm getting the following error:- Here I'm presenting the error part of the code as mentioned in the error image. def _transform(self, X, handle_unknown='error'): X_list, n_samples, n_features = self._check_X(X) X_int = np.zeros((n_samples, n_features), dtype=np.int) X_mask = np.ones((n_samples, n_features), dtype=np.bool) if n_features != len(self.categories_): raise ValueError( "The number of features in X is different to the number of " "features of the fitted data. The fitted data had {} features " "and the X has {} features." .format(len(self.categories_,), n_features) ) The exception line is if n_features != len(self.categories_): although I've checked that OneHotEncoder part and it seems ok to me. -
Django view not redirecting properly
I've been trying to get this working all day and finally now asking for help, sometimes this runs and sometimes is doesn't yet putting a stop in the debugger it never hits it. There is obviously something seriously wrong with this, but I can' see it for the life of me. class ProjectDelayedView(RedirectView): def get_redirect_url(self, *args, **kwargs): slug = self.kwargs.get("slug") print(slug) obj = get_object_or_404(Project, slug=slug) if obj.delayed is False: obj.delayed = True else: obj.delayed = False obj.save() return redirect('www.google.com') Ideally I want it to redirect back to the page I was at previously, but at this point just directing to anything at all would help, hence the return redirect to google on a RedirectView. All I know is that if I paste the url into the address bar, it goes to a blank page and looks to be in constant search, as the refresh icon in firefox stays as X. Stopping the page and then refreshing it again does the action in the database, but I can't get the redirect to work at all, it should go back to the same page I was on preferably.