Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Python models.py indentation error
I have the following code and an error that says 'inconsistent use of spaces and indentation' but I cannot see what has been done wrong? class Song(models.Model): album=models.ForeignKey(Album, on_delete=models.CASCADE) file_type=models.CharField(max_length=10) song_title=models.CharField(max_length=250) def __str__(self): return self.song_title The code above it for another class is exactly the same, but it works class Album(models.Model): artist=models.CharField(max_length=250) album_title=models.CharField(max_length=500) genre=models.CharField(max_length=100) album_logo=models.CharField(max_length=1000) def __str__(self): #this is a string representation of this object - useful for testing/viewing purposes return self.album_title+""+self.artist The error appears to be in the line that returns the string representation of the Song object def __str__(self): return self.song_title More specifically the error seems to point to this line: def __str__(self): (if you note its position above int he Song class, the indentation looks fine...) Can anyone spot the error or suggest a fix? -
Is it better to use path() or url() in urls.py for django 2.0?
In a django online course, the instructor has us use the url() function to call views and utilize regular expressions in the urlpatterns list. I've seen other examples on youtube of this. e.g. from django.contrib import admin from django.urls import include from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] #and in polls/urls.py urlpatterns = [ url(r'^$', views.index, name="index"), ] However, in going through the Django tutorial, they use path() instead e.g.: from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), ] Furthermore regular expressions don't seem to work with the path() function as using a path(r'^$', views.index, name="index") won't find the mysite.com/polls/ view. Is using path() without regex matching the proper way going forward? Is url() more powerful but more complicated so they're using path() to start us out with? Or is it a case of different tools for different jobs? -
python manage.py collectstatic is loading the wrong (local) settings
I am using cookiecutter-django .env design to load different settings depending on environment. Running locally should use "local.py" settings and wunning in aws elatic beanstalk, it should load "dev.py". Both import from "common.py". Running the server in AES with dev settings works, but collectstatic fails, because it tries importing the local settings instead of dev settings. How can the EC2 instance run collectstatic and load the (appropriate) dev.py settings? -
Django Rest How can I show data from a foreign key relationship
Everyone! Using django's rest framework. I created a basic api. Now I want to show my foreign key relationship in my ReleaseDate Model to my Game Model. A game can have one or multiple release dates. My models: # Create your models here. class Game(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) url = models.CharField(max_length=100) created_at = models.BigIntegerField() updated_at = models.BigIntegerField() summary = models.CharField(max_length=2000) first_release_date = models.BigIntegerField() category = models.SmallIntegerField() cover = models.CharField(max_length=100) def __str__(self): return self.name class ReleaseDate(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, on_delete=models.CASCADE) created_at = models.BigIntegerField() updated_at = models.BigIntegerField() category = models.SmallIntegerField() platform = models.SmallIntegerField() date = models.BigIntegerField() region = models.SmallIntegerField() y = models.SmallIntegerField() m = models.SmallIntegerField() human = models.CharField(max_length=10) Now on the API side, I created two serializes for both of my models class ReleaseDateSerializer(serializers.ModelSerializer): class Meta: model = ReleaseDate fields = '__all__' class GameSerializer(serializers.ModelSerializer): #release_date = ReleaseDateSerializer(many=True, read_only=True) class Meta: model = Game fields = '__all__' #fields = ('name', 'url', 'release_date') I want to get all the Game's release dates to show in the JSON Game object. Thank you -
Timezone offset changes in django/postgres
I'm having an issue with Django changing the UTC offset of my data, not entirely at random, but with no prompting that I can see. When I observe it as a datetime.datetime object before saving (via Model.objects.Create()): 2017-12-29 05:16:00-08:00 When I check the column manually in Postgres: 2017-12-29 06:32:00-07 (the -07 offset corresponds to my local timezone) When I re-load the object in Django: 2017-12-29 13:16:00+00:00 How can I get it to preserve the original UTC offset? Do I need to save it in a different way? -
Linking User Profile Page to a model in Django
I am new to Django. i have created a model for a simple textbox app as follows: enter code here from __future__ import unicode_literals from django.db import model class TODO(models.Model): task= models.CharField(max_length=200) Also ,I have created a user login portal.Now I want to activate the model and redirect the user to that page when he logs in.Please help me with that. -
some issue with migrate django saleor e-commerence
I am on ubuntu virtual machine on mac laptop.. I want run saleor e-commerence storefront for django and Django based on saleor docs i solve many errors and now I don not know what to do with the maybe my last error , this in may manage.py file : #!/usr/bin/env python3 mport os import sys if name == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE","saleor.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) and this is installed_apps part of settings.py file: INSTALLED_APPS = [ django.setup() # External apps that need to go before django's 'storages', # Django modules 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sitemaps', 'django.contrib.sites', 'django.contrib.staticfiles', 'django.contrib.auth', 'django.contrib.postgres', 'django.forms', # Local apps 'saleor.userprofile', 'saleor.discount', 'saleor.product', 'saleor.cart', 'saleor.checkout', 'saleor.core', 'saleor.graphql', 'saleor.order', 'saleor.dashboard', 'saleor.shipping', 'saleor.search', 'saleor.site', 'saleor.data_feeds', # External apps 'versatileimagefield', 'django_babel', 'bootstrap3', 'django_prices', 'django_prices_openexchangerates', 'graphene_django', 'mptt', 'payments', 'webpack_loader', 'social_django', 'django_countries', 'django_filters', 'django_celery_results', 'impersonate', 'phonenumber_field', ] when i run : python manage.py migrate i got this error: File "/home/sahar/Desktop/last/saleor/saleor/settings.py", line 154 'storages', ^ SyntaxError: invalid syntax did anyone has the same issue? -
Django page failing to render - error in views.py url path
I have an error arising in the views.py file, and as a result I cannot load the page. music/views.py from django.shortcuts import render from django.http import HttpResponse from .models import Album # Create your views here. #each URL is connected to a view or an Http Response def index(request): all_albums = Album.objects.all() html = ' ' for album in all_albums: url= '/music/' + str(album_id) + '/' html +='<a href="' + url + '">'+album.album_title+'</a><br>' return HttpResponse(html) def detail(request,album_id): return HttpResponse("<h2>Details for Album id:" + str(album_id) + "</h2>") The line causing the error is presumably: url= '/music/' + str(album_id) + '/' The actual (page) error is: NameError at /music/ name 'album_id' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/music/ Django Version: 2.0 Exception Type: NameError Exception Value: name 'album_id' is not defined Exception Location: C:\Users\User\Desktop\website\music\views.py in index, line 13 Python Executable: C:\Python34\python.exe Python Version: 3.4.3 Python Path: ['C:\\Users\\User\\Desktop\\website', In a separate test album_id does seem to be "accessbile" in that http://127.0.0.1:8000/music/1/ will correctly load the page (the album id number is displayed on the page). The error points to the code above, but I cannot see how to fix it. Following the New Boston Tutorials and I have googled to see … -
Regex in url not working correctly
I have the following url path. path('(?P<address>add_[a-zA-Z0-9]{60})', views.detail, name='Account Detail'), Here is what I am using: add_3tz8jreirf54a5nknzksqqfbtxchxdy34zds9anxnw4j9sfkzujay6u441pk I've checked on RegExr and all seems fine but I'm getting a 404 error. -
How to search text containing non-ASCII characters with Django icontains query?
I would like to search for text that contains non-ASCII characters using ASCII search keywords, so that 't' matches 'ṭ'. For example, given a Book object with Sanskrit title 'Aṣṭasāhasrikā-prajñāpāramitā-sūtra' in field title, I would like the following query to return it: Book.objects.filter(title__icontains='prajna') -
What is the difference between postgres and psotgres_psychopg2 as a database engine for django?
I have worked with python for a while, but never django. I am taking over a project that a different employee made before leaving our company. I am wondering if there is a difference between the option postgesql and postgres_psycopg2 as a database driver for django. In some articles and the docs about how to set up a django project I have seen just postgresql and in others I have seen the postgres_psycopg2. I couldn't find anything in the docs (here or here) that mentioned psycopg2, so is this just the old way of writing the option? Is one just an alias for the other or are they actually different enignes? I also couldn't find any other SO questions on this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql',# here I also saw postgres_psycopg2 'NAME': 'premqcsite', 'USER': 'django_user', 'PASSWORD': 'Encepta_123', 'HOST': 'localhost', 'PORT': '5432', }} -
How to predict data faster in Django app deployed on Heroku?
I have an algorithm in my Django app deployed on Heroku which predicts data. My problem is that this function works many hours to generate predictions. I need to do it faster. Much faster. The faster the better. It seems to me that the best solution would be to predict each object separately and asynchronously. I mean running predict(name1), predict(name2), predict(name3) ... at the same time. Any ideas how can I solve my problem? @sched.scheduled_job('cron', day_of_week='mon-fri' , hour=19, minute=35) def scheduled_job(): objects = Object.objects.all().values("name") for key in objects: try: predict(key["name"]) except: print("Error in prediction") -
Best appraoch to have different user types in my project?
Desired Outcome: To have a website that has two different types of users. There are the main users who are the customers. There are also the employee users. The customers has an address, an appointment. The employees have available hours to work. On this website users who create an account through the site will automatically become customer accounts. They will have their own dashboard which displays different fields than the employee users see. Steps To Success: Should there be a separate app for the main site where the customers create their account? And then there will be a separate app for the employees. And each app will have their own objects specific to that user type? -
i can't install mysqlclient and pillow in python
i want to install mysqlclient but it returns me (venv)amir@amg76:~/Documents/Computer/Python/Django/vira/virasciencecom$ pip3 install mysqlclient==1.3.7 Collecting mysqlclient==1.3.7 Using cached mysqlclient-1.3.7.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-c5i8m5ok/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-c5i8m5ok/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-c5i8m5ok/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-c5i8m5ok/mysqlclient/ the same thing happen when i try to install pillow and i use python 3.6 and ubuntu 17.10 can any body help me? -
Django Rest Framework Invalid serialization
I am trying to serialize a dictionary into Relationship Serializer, the data gets serialized fine but the validator returns false RelationshipSerializer: class RelationshipSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=False) related_user = UserSerializer(read_only=False) class Meta: model = models.Relationship fields = ( 'user', 'related_user', ) View: related_user_id = body["related_user"] related_user = models.User.objects.get(id=related_user_id) user = self.get_object() user_serializer = serializers.UserSerializer(user).data related_user_serializer = serializers.UserSerializer(related_user).data # user_serializer and related_user_serializer return valid data. data = {"user": user_serializer, "related_user": related_user_serializer} serializer = serializers.RelationshipSerializer(data=data) # Serializer works fine, it prints out data correctly serializer.is_valid() # Returns false return Response(serializer.data) When I log serializer.errors I get { "required": "This field is required.", "null": "This field may not be null.", "invalid": "Invalid data. Expected a dictionary, but got {datatype}." } I tried setting my serializer fields to null = True and required = False but still no luck -
Django using admin features for frontend
I am building out a Django application and so naturally followed the Django tutorials found in the docs. What I realized was that the admin app really offers a great deal of frontend support. Take a look at the following: And all that I needed was to create a short couple of classes in admin.py within the polls app (specified in tutorial 7). from django.contrib import admin from .models import Question, Choice class ChoiceInLine(admin.TabularInline): model = Choice extra = 3 # customize form for question class QuestionAdmin(admin.ModelAdmin): # display more than just string on "change list" page list_display = ('question_text', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question_text'] # title, field : Model.var fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] # add 3 Choice Models after fieldsets inlines = [ChoiceInLine] admin.site.register(Question, QuestionAdmin) admin.site.site_header = "Other Name" Most developers would appreciate the simplicity of the above script. I didn't need to write a single line of HTML, CSS, or Javascript. I was able to embed a list of my class Question into a viewer friendly format and I am able to use the search bar to filter for specific results. Now only one problem. I … -
Django 2.0 error in urls.py relating to views.py
I have the following code that seeks to load a page localhost/music/1 ...I have been following a tutorial that uses Django 1.9. The code that is throwing up the error is: music/urls.py # this is matching /music/1 where 1 is the album id path('(?P<album_id>)[0-9]+)/', views.detail, name='detail'), #note album_id is the variable being stored which can be passed music/views.py def detail(request,album_id): return HttpResponse("<h2>Details for Album id:" + str(album_id) + "</h2>") The error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/music/2 Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: admin/ music/ [name='index'] music/ (?P<album_id>)[0-9]+)/ [name='detail'] videos/ The current path, music/2, didn't match any of these. Can anyone post a fix/answer that will solve the problem. Thanks -
Django QuerySet union operator is not commutative after intersection
I use python 3.4.2 and django 2.0. My models.py class Solution(models.Model): name = models.CharField(max_length=200) Then in python console I do this: >>>a = Solution.objects.all().filter(id="1") >>>b = Solution.objects.all().filter(id__in=["1","2"]) >>>c = Solution.objects.all().filter(id="3") >>>ab = a.intersection(b) >>>abc = ab.union(c) >>>cab = c.union(ab) >>>abc <QuerySet [<Solution: Solution-id1>, <Solution: Solution-id3>]> >>>cab <QuerySet [<Solution: Solution-id1>]> Why abc != bca?? -
How to test sending mails in Django celery?
We use Django version 1.6, I came across this GitHub repo but their version required is 1.8+. Is there any other thing you guys have used. Kindly let me know. -
Include many-to-many field in admin page for reverse related model
For the model below I want to create an admin page where I directly can edit the user_permissions for the related django_user. How would I do that? from django.contrib.auth.models import User from django.db import models class MyModel(models.Model): django_user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) -
500 error when posting django rest
I am trying to post data using DRF modelviewsets and Axios. I have tried a couple different options so far with the same result, 500. I am able to get data using axios.get but not able to post data. I am new to rest and using ajax so I apologize if it is something obvious. Axios call var csrftoken = Cookies.get('csrftoken'); axios({ method: 'post', url: "/api/schedules/create", data: { "emp": this.emp.emp, 'start_time': this.startTime, "end_time": this.endTime, "date": this.today, "location": this.location }, headers : {"X-CSRFToken" : csrftoken } }) }, Serializer class SchedSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = ( 'location', 'emp', 'date', 'start_time', 'end_time' ) View class SchedViewSet(viewsets.ModelViewSet): queryset = Schedule.objects.all() serializer_class = serializers.SchedSerializer -
Associating a python social account with multiple django users
I want to connect the same (google-oauth2) account with multiple Django users using this credentials model: class CredentialsModel(models.Model): id = models.OneToOneField(User, primary_key=True) credential = CredentialsField() However, when I do so I get the error This google-oauth2 account is already in use. in social_core/pipeline/social_auth.py in associate_user. So I modified the pipeline with custom associate_user and social_user methods and removed the if user and social.user != user check in social_user: def social_user(backend, uid, user=None, *args, **kwargs): provider = backend.name social = backend.strategy.storage.user.get_social_auth(provider, uid) if social: # no `AuthAlreadyAssociated` when `user and social.user != user` user = social.user return {'social': social, 'user': user, 'is_new': user is None, 'new_association': social is None} Now the error is gone, but the (second) Django user did not get associated. The first user's association did not change. -
Datepicker covers the input field within a modal
The datepicker element is not created correctly within a modal, it covers the input field and I can not visualize the data html: <div id="datepicker" class="input-append date col-md-12" > <input type="text" class="form-control"> <span class="add-on"> <span class="arrow"></span> <i class="fa fa-th"></i> </span> </div> js: <script src="{% static 'assets/plugins/bootstrapv3/js/bootstrap.min.js' %}" type="text/javascript"></script> $("#datepicker").datepicker({ format: "dd/mm/yyyy", startDate: "01-01-2015", endDate: "01-01-2020", todayBtn: "linked", autoclose: true, todayHighlight: true, container: '#myModal modal-body', zIndex: 2048, }); -
Difference between named urls in Django?
What is the difference between these two named urls in Django? re_path('articles/(?P<year>[0-9]{4})/', views.year_archive), path('articles/<int:year>/', views.year_archive), They appear to do the same? -
Django - getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
I am learning django framework from last 4 days. Today I was trying to retrieve a URL in HTML template by using {% url "music:fav" %} where I set the namespace in music/urls.py as app_name= "music" and also I have a function named fav(). Here is the codes: music/urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ path("", views.index, name="index"), path("<album_id>/", views.detail, name="detail"), path("<album_id>/fav/", views.fav, name="fav"), ] music/views.py def fav(request): song = Song.objects.get(id=1) song.is_favorite = True return render(request, "detail.html") in detail.html I used {% url 'music:detail' %} But I dont know why this is showing this error: NoReverseMatch at /music/1/ Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['music\/(?P[^/]+)\/$']