Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django static files are sometimes not serving
Dear Stackoverflow community. I have for a while now been struggling with my static files during development in my Django project. The problem is mainly that my stylesheets are sometimes working and sometimes not. Example - my base.html's stylesheet base_style.css is always loading, but when I add a stylesheet for the file home.html which I have loaded through the jinja template tags It sometimes works and sometimes not, the same goes for my other views. Using python3 and Django 1.11.5 Here is my settings file (Static) = STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") Here is my template Base.html = {% load static %} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="apple-touch-icon" sizes="180x180" href="{% static 'img/favicons/apple-touch-icon.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'img/favicons/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'img/favicons/favicon-16x16.png' %}"> <link rel="manifest" href="{% static 'img/favicons/manifest.json' %}"> <link rel="mask-icon" href="{% static 'img/favicons/safari-pinned-tab.svg' %}" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> <title>Leaf</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet"> <link rel="stylesheet" href="{% static 'mainapp/base_style.css' %}" type="text/css" /> </head> <body> <!-- NAVBAR --> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light navbar-custom text-uppercase"> <img src="{% … -
Django rating model with m2m
I'm confused with my django models, My models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) picture = models.ImageField(upload_to="photos/", default="photos/none/default.png") film = models.ManyToManyField(Film) class Film(models.Model): title = models.CharField(max_length=60) year = models.IntegerField(choices=YEARS) image = models.ImageField(upload_to="images/", default="images/none/blank_poster.jpg") def __str__(self): return self.title and now I trying to make a ratings for my film, when user adding a film to his list. I tried M2M with through, but it wasn't exactly what I wanted, because user could add the same film several times and another problem with it was remove single film from list. Now i thinking about additional models like this: class FilmRating(models.Model): user = models.ForeignKey(User) film = models.ForeignKey(Film) rate = models.IntegerField(choices=CHOICES) Im glad If you can point me to the correct way to solve this problem, In future I want probably to store all rating from users for set average rate. -
Django annonate Sum under a condition
I have a model which have fields like class Points(models.Model): player = models.ForeignKey(Player) points = models.IntegerField() datetime = models.Datetime() I want to get the sum of points on weekly basis with week start ie date. So let's say week start from 22nd October then it should accumulate point from 22nd October to 28th October. I tried the below query but it doesn't give me points on weekly basis since. The points aren't available for every player on each day so I need total weekly points scored. Points.objects.values('datetime').annonate(weekpoints=Sum('points')).order_by('-datetime') It returns points on daily basis not on weekly basis. -
Is there an easy way to create a user login?
I would like to have normal users (not admins) who can log in. By default when doing a project in Django it is enough to create a superuser and you can already authenticate and manage the site, also if I created a model named Question I can create, edit and delete questions from the admin dashboard (like in the tutorial part 2) adding just this code: from .models import Question admin.site.register(Question) I would like to replicate this, I mean, to have a similar login template with normal users and a dashboard where these normal users can see, create, edit and delete Question instances that belongs to them, ie., where they can manage only their questions, but obviously making them not be able to edit other users or groups, how could I do it? would it be difficult? Thanks! -
django forms - change the value of the fields
I have these models class Student(Model): student_no = CharField(max_length=10) name = CharField(max_length = 50) def __str__(self): return self.name class ClassList(Model): students = ForeignKey(Student) In forms: class ClassListForm(ModelForm): class Meta: fields = ['students'] When I render this, the template shows a select box with the students in it. However, the students are displayed based on what the def __str__() function contains. How do you change the values of the students field so that it will display their student_nos without changing the def __str__() function -
How to Make django project live
I have developed few websites with Django. Now i want to see them live. I have already purchase VPS server hosting. All are setup like pip/applications . Also when i am running server it show Django version 1.11, using settings 'wer.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But i don't know why it's not showing in my domain. What are the changes i need to make in settings.py file to show it in my domain or host it live. Is it not possible with the same command :- python manage.py runserver -
Pass django variable to javascript file without security issues
In my project there's a module where user can see details about product and add products to cart. For this he needs to specify the number of products he wants to add. It looks like For this I have a + and - icon. I have a js file where it increments or decrements each time + or - has been clicked. Now, what I want is this: A user can add products but if the total number exceeds the number of products stored in the database, he can't add products even if he click the + button. For example, if there are 4 items and he clicked 5 times then on the 5th click the amount will remain 4, won't increase. So I need a django variable in my js file. I looked up how to do that, and I found some solutions. Some solution says var data = '{{data|escapejs}}' this while some solution says <script> var myTable = {% autoescape off %}{{ table_data }}{% endautoescape %}; </script> But I don't want to embed js on my html like this. Here is my js file: function incrementValue() { var value = parseInt(document.getElementById('quantity').value, 10); value = isNaN(value) ? 0 : … -
Django Bootstrap Dropdown Menu Empty
I want to extract a list of objects and put them in a drop down menu. I already did that and it worked, but not on a dropdown menu, maybe the problem is in my HTML I don't know. Here is my html part: <ul class="dropdown-menu" role="menu"> {% for s in structures %} <li><a href="#">{{ s.id }}</a></li> {% endfor %} </ul> I already did this to display structures in a table in another html template and it worked: here is the working code: <tbody> {% for structure in structures %} <tr> <td><center>{{ structure.name }}</center></td> <td><center>{{ structure.created_at }}</center></td> <td><center>{{ structure.updated_at }}</center></td> <td><center>{{ structure.file }}</center></td> <td> <a href="/edit/{{ structure.id }}" class="btn btn-primary btn-xs">Modifier</a> <a href="/delete/{{ structure.id }}" class="btn btn-danger btn-xs">Supprimer</a> </td> </tr> {% endfor %} </tbody> Thoughts? Thanks! -
UserCreationForm save user to the data base but redirect back to sign_up form not to success url
I'm face this stranger problem on django when creating user and use UserCreationForm to register user but when i submit user form all data get saved but it redirect back to sign_up form while it was suposed to redirect to success url.I don't know what might cause it. Here is MyCustomUser model: class MyCustomUser(AbstractBaseUser): email = models.EmailField(max_length=50, verbose_name='email', unique=True) first_name = models.CharField( max_length=15,blank=False) last_name = models.CharField( max_length=15,blank=True) slug = models.SlugField(null=True, unique=True) is_staff = models.BooleanField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_full_name(self): full_name = '{0} {1}'.format(self.first_name, self.last_name) return full_name.strip() def get_short_name(self): return self.first_name def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin def __str__(self): return self.first_name Here is my UserCreationForm class SignUpForm(UserCreationForm): first_name = forms.CharField(widget=forms.TextInput( attrs={'class':'form-control', 'placeholder':'First Name'})) last_name = forms.CharField(widget=forms.TextInput( attrs={'class':'form-control','placeholder':'Last Name'})) email = forms.EmailField(widget=forms.EmailInput( attrs={'class':'form-control', 'placeholder':'Email'})) password1 = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control', 'placeholder':'Password'})) password2 = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control', 'placeholder':'Repeat the password'})) class Meta: model = MyCustomUser fields = ['first_name','last_name','email', 'password1', 'password2'] Her is the function that render SignUpForm def sign_up(request): form = SignUpForm() if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) #create instance of first_name an last_name full_name = '{0} {1}' … -
DJango Regex not matching
I have trouble matching urls using regex in Python/DJango. Here is the url it needed to fetch http://127.0.0.1:8000/blog/2017/11/3/1/ Here is the code: from django.conf.urls import url from blog import views app_name = 'blog' urlpatterns = [ url(r'^blog/$', views.blog, name='archive'), url(r'^blog/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/(?P<id>[0-9]+)/$', views.blog_article, name='blog_article'), ] # regex -
Multiple Models in a view with exclusion
I'm new to Django and using version 1.11 with Python 3.6. I'm not sure if what i'd like to do is possible, but currently I'm pulling in data on a template for my custom user model. When I try to pull data from another model that is joined in the data model it doesn't show. In my views.py I created the following to get the user and application list detail: def profile(request): args = {'user':request.user} return render(request, 'accounts/profile.html', args) def applicationdetail(request, ntname): user = get_object_or_404(User, pk=formattedusername) applicationlist = QVReportAccess.objects.all() applicationaccess = Reply.objects.filter(user=ntname) context = {'user' : request.user, 'applicationdetail' : QVReportAccess} return render(request, 'accounts/profile.html', context=context) Now for my Template I'm just trying to pull in the application associated on the formattedusername to the ntname. After I get the current application list, I want to get the available applications the user currently does not have access to that exist in the report list table that don't exist in the QVReportAccess table. {% block head %} <title> Profile </title> {% endblock %} {% block body %} <div class = "container"> <h2>{{ user.username }}</h2> <ul> <li>Email: {{ user.email }}</li> <li>Employee First Name: {{ user.first_name }}</li> <li>Employee Last Name: {{ user.last_name }}</li> <li>Coid: {{ user.coid … -
Download an xml file from S3 directly to client (without first downloading file into memory)
I'm drawing a blank on how to do this. I want to start a download from S3 in a Django view, and stream the download directly to the client. i.e., avoid downloading the whole thing into memory and then transferring to the client. I figured out so far that StreamingHTTPResponse would be involved somehow but I'm having trouble putting the pieces together. I'm using Boto3, Python3, and Django 1.11. -
My Django dont show anything
Thank you very much guys! that issue has solved!(Here is my old post Django name 'admin' is not defined ) but it show nothing. I want to show the content in header.html & home.html here is the code personal/views from django.shortcuts import render def index(request): return render(request,'personal/templates/personal/home.html') And here are the code of home and header {% extends "personal/header.html" %} {% block content %} <p> Hey welcome to my very first project by Django :D </p> {% include "personal/includes/"htmlsnippet.html %} {% endblock %} header: <!DOCTYPE html> <!DOCTYPE html> <html lang="en"> <head> <title>Harry-Phuc Coi</title> <meta charset="utf-8"> </head> <body class="body" style="background-color: #f6f6f6f6"> <div> {% block content %} {% endblock %} </div> </body> </html> And here is my path my path -
Deploying Django App on IIS - Secret Key Improperly Configured
I have a Django app deployed on IIS. I am currently working through Django's deployment checklist to secure the app. I have an environment variable with the SECRET_KEY stored as the value. I am accessing the SECRET_KEY with this: SECRET_KEY = os.getenv('SECRET_KEY') print(SECRET_KEY) When I view the IIS hosted app, I get a 500 error. When I use runserver to host the same app, the development server runs with no issues, and the SECRET_KEY is printed out (and is therefore accessed from settings.py). However, this issue occurs when the app is viewed in the browser: ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. How is the SECRET_KEY empty if it's printed out in the command line? -
How to count days belonging to a given month in the range of two Python datetimes?
I have two Python datetime and I want to count the days between those dates, counting ONLY the days belonging to the month I choose. Example: If I have 2017-10-29 & 2017-11-04 and I chose to count the days in October, I get 3 (29, 30 & 31 Oct.). I can't find anything to facilitate the job so I think I'm going to iterate over the days using datetime.timedelta(days=1) and increment a count each time the day belongs to the month I chose. What do you think? Is there a better way to achieve this? I'm using Python 2.7.10 with the Django framework. -
RuntimeError when run my python code
I tried to run my code but I'm faced with this error: File "", line 1, in runfile('C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners/run_multiwalker.py', wdir='C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners') File "C:\Users\niloo\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\Users\niloo\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners/run_multiwalker.py", line 7, in from runners import RunnerParser File "", line 961, in _find_and_load File "", line 946, in _find_and_load_unlocked File "", line 881, in _find_spec File "", line 855, in _find_spec_legacy File "C:\Users\niloo\Anaconda3\lib\site-packages\pyximport\pyximport.py", line 253, in find_module fp, pathname, (ext,mode,ty) = imp.find_module(fullname,package_path) File "C:\Users\niloo\Anaconda3\lib\imp.py", line 269, in find_module raise RuntimeError("'path' must be None or a list, " RuntimeError: 'path' must be None or a list, not What should I do? -
authentication and authorization implementation for web api using saml and token
I am working on project which have following structure- Frontend [client] : angular2 + html Web services [server] : Django Database : mongoDB Currently, I am not using any request authentication or authorization. For SSO authentication I have to use SAML Please suggest me a better and most secure approach to implement from what Currently I have in my mind is - Authenticate client login request against SAML on django side using pysaml generate self encoded token and pass it client for every request authorization I am not much experienced guy but I am learning through reading and mistakes. I didn't found any proper solution for my scenario. It will be big help for me If you have better and most secure approach which should not change technology and tools I am using. Also i am not allowed to use any other database than MongoDB. -
Django: Create multiple objects from one view
I am building a website which allows teachers to ask questions to their students, and get answers back from their students. Each 'review' will consist of a title, description and then a bunch of questions related to the review via a foreign key. The questions would be added one by one and to add more Javascript will be used to add the additional fields. The way I am currently thinking of doing this by having one view, which first processes a form that creates the Review object with the title, description and User that made it. It would then take all the questions the user had entered create an object for each of these using the ID of the review that was just created. I made a simple form and a view that makes the Review block, however I dont know how to go about handling the questions the user wants to add. If there are any other better ways of doing this, please let me know! Thanks -
Django migration slow and resource intensive even with "--fake"
I'm using "DATABASE_ROUTERS" and just added migrations to new database. I have 153 migrations on the "default" database and it seems that all of those have to be run on the new database even though they don't apply. My db router's allow_migrate returns False on every migration except for the one "initial" one related to the new database. I faked that one initial migration and then ran manage.py migrate --database new_database and was surprised that after 45 minutes I had to kill the process when it had used up all the memory and all of the swap space! I then tried again but this time with manage.py migrate --database new_database --fake and it seemed to make no difference. My memory and swap usage went through the roof and I had to again kill the process. All this command should be doing is marking all migrations as completed in the "django_migrations" table. What is really happening to cause so many resources to be used? Am I doing something wrong? What is the best way around this issue? Should I just manually create the "django_migrations" table and then populate it myself? -
Django unittest mock queryset from related object
I have the following function: import unittest from unittest import mock def get_payments(order): return order.payments.filter(status='complete').order_by('-date_added) I want to mock the filter method and the order_by to check the arguments with which are called. I tried: @mock.patch('path.Order.payments.filter.order_by') @mock.patch('path.Order.payments.filter') def test_get_payments(self, mock1, mock2): mock1.assert_called_with(status='complete') mock2.assert_called_with('-date_added') Another mock I tried: @mock.patch('path.Payment.objects.filter.order_by') @mock.patch('path.Payment.objects.filter') @mock.patch('path.Order.payments.objects.filter.order_by') @mock.patch('path.Order.payments.objects.filter') In last two mocks I have an error that path.Order does not exists. I already used a direct mock for a query like Payment.objects.filter() and is working, but starting from a related model like Order I failed. The relationship between Order and Payment is how you would expect, one to many. -
Nested array field with different field types
rankings = ArrayField( ArrayField( models.IntegerField() ) ) This array field will hold an array containing nested arrays each containing IntegerField: [[1,2],[3,4]] Is it possible to have the nested array containing different field types: such as date and integer data: [[2017-11-03 14:23:49.349201+01,2],[2017-11-03 14:23:49.349201+01,4]] ? -
Django append string to field in model
I am trying using legacy, read only DB as django.contrib.auth.models.AbstractBaseUser. Problem is that my legacy password field is SHA1 without starting 'sha1$$' string, just hash only, so I need to append extra string to every password. models.py class Tuzytkownik(AbstractBaseUser): login = models.CharField(db_column='LOGIN', max_length=50, unique=True) haslo = models.CharField(db_column='HASLO', max_length=50) password = 'sha1$$' + haslo USERNAME_FIELD = 'login' REQUIRED_FIELDS = [] Obviously password = 'sha1$$' + haslo not working. How I can acheve it ? To be specyfic - haslo returing 40charts hash like 'cf23df2207d99a74fbe169e3eba035e633b65d94' what I need is 'sha1$$cf23df2207d99a74fbe169e3eba035e633b65d94' -
Django: Best way to merge migrations conflicts
I'm currently working on a dev branch and I will need to merge it to master one day. I have up to 20 migrations files on my dev branch and about the same number on master at the moment. I needed to make migrations on both branches which will result in migrations having the same prefix, (ex 0003_auto) In other words, if you have migrations files generated by makemigrations with the same prefix, what is the best/secure way of handling this. Here are two ways I have figured myself (maybe entirely wrong): Deleting all migrations files, merge the code and then running a fresh makemigrations and migrate which will result in only one migration file. Using the flag --merge flag: makemigrations –merge Now, knowing all this I'd like to know what is the best way of handling this. In general, what should I use that will correctly merge conflicts and get me a fresh version of my project with every model updates. -
HyperlinkedIdentityField an null values in django-rest-framework
I've got two models (code is simplified): class Document(models.Model): data = JSONField() class Item(models.Model): name = models.CharField(max_length=10) doc = models.OneToOneField( Document, blank=True, null=True, on_delete=models.SET_NULL ) I would like to make a hyperlink to the Documents details page in the serializer for Item using the HyperlinkedIdentityField. So I have the URL defined: url(r'^doc/(?P<version>[v1|v2]+)/(?P<pk>[0-9]+)/$', doc_details, name = 'api_document_details' ), And I made the following serializer: class ItemSerializer(serializers.ModelSerializer): doc = serializers.HyperlinkedIdentityField( view_name = 'api_document_details', lookup_field = 'doc_id', lookup_url_kwarg = 'pk' ) class Meta: model = Item fields = ('name', 'doc') The problem here is that the doc field in Item is optional. I got an error as there is no URL to be found if the doc_id = None. Could not resolve URL for hyperlinked relationship using view name "api_document_details". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. I would like HyperlinkedIdentityField to return None (null) if the document is not defined in the record. Does anybody know how to do this? I have tried using the SerializerMethodField() methode in which I use the reverse function and return None if I get an exception, but this has two disadvantages: I … -
AttributeError: '…' object has no attribute '***_set'
I'm trying to display a list of 'stats' assigned to a 'Profile' which extenders the User model. I have a ForeignKey relating the Stat to the Profile. However, i need it to work so the user doesn't have to be logged in so they share progress to users who are not a member of the site. I'm trying to use _set for a backwards relationship on the ForeignKey. I think where it's tripping up is because the 'Stat' model and the 'Profile' models are inside different apps. Would this be causing the issue? Code below: class Stat(models.Model): user = models.ForeignKey(User, default=False) image = CloudinaryField('image', default="thumbnail_mqe6ne", blank=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) // Profile view def profile_item(request, id): p = Profile.objects.get(id=7) user_stats = p.stat_set.all() context = { "p": p, "user_stats": user_stats, } return render(request,"profile/profile_share.html", context) The view i'm receiving: 'Profile' object has no attribute 'stat_set' As far as i'm aware using the backwards reference you need to specify the model you are targeting in lowercase. Full stack trace below: Environment: Request Method: GET Request URL: http://localhost:8000/profile/7/ Django Version: 1.10 Python Version: 2.7.14 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'stats', 'home', 'blog', 'challenge', 'haystack', 'ckeditor_uploader', 'ckeditor', 'django_cron', 'anymail', 'templated_email', …