Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not creating instance of Celery app
I'm trying to automate some Django views using Celery but cannot get the Celery workers to start due to Django not importing the Celery instance. This a very similar problem to the post here: Django celery not finding celery module Note that I am not using a virtenv and I am on macos. All packages were installed at the root directory level (the folder for the project that I use for GitHub). I named the project iHand and the application app from the Django setup instructions. app has been added into the INSTALLED_APPS in settings.py to register the app: # Application definitions INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', # Created app ] Instance of the app was created in celery.py: from __future__ import absolute_import, unicode_literals from django.conf import settings from celery import Celery import os # Create a whole instance of the Django project inst = Celery('app') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iHand.settings') inst.config_from_object('django.conf:settings', namespace='CELERY') inst.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Created a package in the __init__.py located in iHand/iHand/ dir: # Load app when Django starts from __future__ import absolute_import, unicode_literals from .celery import inst as celery_app __all__ = ['celery_app'] Created a tasks.py file in iHand/app: # Import views and create tasks out … -
django-crontab is not worked with my django site
I want to learn working with crontab. I have a piece of code cron.py: def my_scheduled_job(): print('hi') f = open('textfile_3.txt', 'tw', encoding='utf-8') f.close() and in setting.py CRONJOBS = [ ('*/1 * * * *', 'file_sharing.cron.my_scheduled_job') ] But it`s not worked. I tried a lot of choices. Maybe u can help me? -
How to create a object with nested objects in Django Rest Framework
Creating my first Django app ever here. I am having a problem with inserting my Route object. Here's my models.py: class Location(models.Model): location_id = models.AutoField(primary_key=True) location_name = models.CharField(max_length=50) location_lat = models.FloatField() location_log = models.FloatField() def __str__(self): return self.location_name class Route(models.Model): route_id = models.AutoField(primary_key=True) route_code = models.CharField(max_length=50) origin_location = models.OneToOneField(Location, related_name="origin", on_delete=models.PROTECT) destination_location = models.OneToOneField(Location, related_name="destination", on_delete=models.PROTECT) waypoint1_location = models.OneToOneField(Location, related_name="waypoint1", on_delete=models.PROTECT, blank=True, null=True) waypoint2_location = models.OneToOneField(Location, related_name="waypoint2", on_delete=models.PROTECT, blank=True, null=True) route_duration = models.DurationField(blank=True, null=True) def __str__(self): return self.route_code What I basically want is to have a Route, with origin and destination as mandatory and the waypoints optional. First, I have a form page where the user creates the Location objects independently. Then, I have another form page, where the user creates the Routes. It selects in the form the Location objects - one for origin, one for destination and optionally waypoint1 and waypoint2 So, in that Route creation, I obviously don't want to create a new Location. It is already there. I only want to link the new route object to the already existing location objects. My serializers.py is: class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = '__all__' class RouteSerializer(serializers.ModelSerializer): origin_location = LocationSerializer(many=False, required=True) destination_location = LocationSerializer(many=False, required=True) waypoint1_location … -
How to change redirect uri? Django - Allauth
I am trying to use Allauth to authenticate with google however I get a uri mismatch error. The app is currently on a development server with a domain ex. live.example.com. I can change the domain within the google app settings and my django app to localhost and everthing works. I am trying to use my domain with Allauth and it is not working I tried changing the site_id and setting different values for that. I am able to use the response from Allauth and manually add the domain and everything works. But when the request is sent it sets the url to localhost because it doesn't understand the proxy. Error: redirect_uri_mismatch The redirect URI in the request, http://localhost:5500/accounts/google/login/callback/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/XXXXXX288-gm2jiuh2o8XXXXXXXXXcc6n11d4j5sr.apps.googleusercontent.com?project=5XXXX82XX Learn more Request Details client_id=X9XXXXX82X8-gXXXXh2o88ejglkXXXcc6n11d4j5sr.apps.googleusercontent.com redirect_uri=http://localhost:5500/accounts/google/login/callback/ scope=email profile response_type=code state=XXXtpODloQK access_type=online -
Probelm with Django manage.py runserver provides errors
I am new to Python and Django. I am trying to run my manage.py but i have this problem enter code here Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Nouha\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Nouha\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Nouha\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Nouha\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Nouha\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Nouha\AppData\Local\Programs\Python\Python37- 32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'webapp' I tried all solutions in stackoverflow but I still have the same problem :( Can anyone help me please ?! -
how to for loop the bootstrap grid
I'm trying to make it like the following: https://getbootstrap.com/docs/4.3/examples/pricing/ it shows the screen divided into three section so it should be like this I think... <div class="row mb-2"> <div class="col-4 bg-danger"> .col-4 </div> <div class="col-4 bg-warning"> .col-4 </div> <div class="col-4 bg-success"> .col-4 </div> </div> But the problem is I am using django jinja template and for loop. so it groups the whole content. This is my code but it won't do what's like in the link <div class="row"> <div class="col-6 col-md-4"> <div class="card"> {% for all_episode in episode %} <a href="{% url 'episode_detail' slug=all_episode.slug %}"><img class="card-img-top" src='{{all_episode.image.url}}'></a> <div class="card-body"> <h5 class="card-title"> <a href="{% url 'episode_detail' slug=all_episode.slug %}">{{ all_episode.title }}</a> </h5> <p class="card-text">{{ all_episode.story |slice:":100" }}...</p> </div> <div class="card-footer"> <small class="text-muted"> <span class="h5"> <a href="{% url 'series_detail' slug=all_episode.series.slug %}">{{ all_episode.series }}</a> </span> / <span class="h6"><a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season }}</a></span></small> </div> {% endfor %} </div> </div> -
Django, uwsgi with NGINX -- uwsgi will not start
I, trying to configure a test webserver. My steps: cd /home sudo mkdir webapp cd webapp sudo mkdir testproject cd testproject sudo python3 -m venv env source env/bin/activate pip3 install django sudo django-admin startproject testproject cd testproject/testproject pip install django sudo nano settings.py update allowed hosts and database cd /home/webapp/testproject/testproject python manage.py runserver 0.0.0.0:8000 check if django page visible, yes Django demopage is visible. Stop server sudo uwsgi --http 0.0.0.0:8000 --home /home/webapp/testproject/env --chdir /home/webapp/testproject/testproject --wsgi-file /home/webapp/testproject/testproject/testproject/wsgi.py Check if website is up, yes it is.Stop server cd /home/webapp/ mkdir uwsgi cd uwsgi mkdir sites cd sites nano testproject.ini [uwsgi] home = /home/webapp/testproject/env chdir = /home/webapp/testproject/testproject wsgi-file = /home/webapp/testproject/testproject/wsgi.py http = 0.0.0.0:8000 socket = /home/webapp/uwsgi/testproject.sock vacuum = true chown-socket = www-data:www-data chmod-socket = 660 For start on boot sudo nano /etc/systemd/system/uwsgi.service [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c ‘mkdir -p /run/uwsgi; chown www-data:www-data /run/uwsgi’ ExecStart=/usr/local/bin/uwsgi --emperor /home/webapp/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target NGINX configuration sudo nano /etc/nginx/sites-available/testproject server { listen 1.2.3.4:80 default_server; location / { include uwsgi_params; uwsgi_pass unix:/home/webapp/uwsgi/testproject.sock; } } sudo ln -s /etc/nginx/sites-available/testproject /etc/nginx/sites-enabled # checking if syntax is ok # enabling nginx and uwsgi to start at boot sudo nginx -t && sudo systemctl enable nginx && sudo … -
Value error dictionary update sequence element #0 has length 1; 2 is required
I want to write a context processor, so that the list can be seen anywhere in the application in django (version 2.1). I'm getting an error: ValueError at / dictionary update sequence element #0 has length 1; 2 is required def following_issues(request): request_context = RequestContext(request) request_context.push({'following_issues': Issue.objects.filter(followers=request.user.is_authenticated)}) return request_context In my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'base.context_processors.following_issues', ], }, }, ] -
Display User teams in template
I have 3 models - Project, Team and a CustomUser model. I'm trying to display a list of teams which a user is part of on the user's detail page, and display a list of users who are part of the project team on the project's detail page but I'm at a stand-still. # project/users/models.py class CustomUser(AbstractUser): name = models.CharField(max_length=255) # Relationship Fields team = models.ManyToManyField( 'users.Team', related_name="teams", ) class Team(models.Model): # Relationship Fields project = models.OneToOneField( 'projects.Project', on_delete=models.CASCADE, related_name="projects", ) # project/projects/models.py class Project(models.Model): name = models.CharField(max_length=255) project/projects/templates/projects/project_detail.html {% for user in project.team.user.all %} {{ user.name }} {% endfor %} I've tried variations of the above such as {% for user in users.teams.projects.all %} {{ user.name }} {% endfor %} but I can't seem to make anything show. I think I'm doing something simple wrong - I've read through the docs for displaying ManyToManyFields but I'm at a loss! Can anybody point me in the right direction? -
Upload a file and then display contents, django
I will preface this by noting I'm a python beginner. I'm trying to build a very simple app where the user uploads an ics file, and upon submit, the file is parsed and the app displays the contents in a legible format. I'm trying to use FileSystemStorage(), but I can't seem to set it up correctly. This is what my views.py and template looks like. # views.py from django.core.files.storage import FileSystemStorage from django.views.decorators.clickjacking import xframe_options_exempt from icalendar import Calendar, Event from pytz import UTC @xframe_options_exempt def index(request): if request.method == 'POST' and request.FILES['icsfile']: myfile = request.FILES['icsfile'] fs = FileSystemStorage() filename = fs.save(icsfile.name, icsfile) uploaded_file_url = fs.url(filename) g = open(uploaded_file_url, 'rb') gcal = Calendar.from_ical(g.read()) for component in gcal.walk(): if component.name == "VEVENT": summary = component.get('summary') description = component.get('description') start_time = component.get('dtstart') end_time = component.get('dtend') g.close() return render(request, 'ics_parser/index.html', { 'uploaded_file_url': uploaded_file_url, 'summary': summary, 'description': description, 'dtstart': dtstart, 'dtend': dtend, }) return render(request, 'ics_parser/index.html', {}) # index.html <div class="ics-formatter"></div> <div class="row"> <div class="col-sm-6"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="icsfile"> <button type="submit">Upload</button> </form> </div> <div class="col-sm-6"> {% if uploaded_file_url %} <p>{{description}}</p> {% endif %} </div> </div> This is the error I'm getting: Exception Type: NameError Exception Value: name 'icsfile' is … -
why my own app "qa" throws "ImportError no module named qa during makemigrations
I have ceated an app with the name "qa" using Djangorestframewwork in python & Django. While I'm trying to apply makemigrations I get an error, "importError" No module named ap. What could be the possible reason of this issue? I'm very new to Djangorestframewwork. Tried "makemigration" command to apply new changes to my django app "qa" but it's not working, throws "importError" No module named qa. qa is the same app I want to apply to it makemigrations -
uploading multiple files with django and displaying the list of uploaded files
I am trying to upload multiple files using django. On submitting the form after selecting multiple files the page reloads with the message "this field is required" and files are not uploaded. models.py from django.db import models # Create your models here. class Document(models.Model): title = models.CharField(max_length=255, blank=True) file = models.FileField(upload_to='docs/') forms.py from django import forms from .models import Document class DocumentForm(forms.ModelForm): file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Document fields = ('file', ) views.py def main(request): documents = Document.objects.all() if request.method == "POST": form = DocumentForm(request.POST and request.FILES) if form.is_valid(): files = request.FILES.getlist('file') for f in files: f.save() else: form = DocumentForm() return render(request, 'main.html', {'form':form, 'documents':documents}) urls.py urlpatterns = [ path('', views.home, name='home'), path('main/', views.main, name='main'), path('admin/', admin.site.urls), ] main.html <form method="POST"> {% csrf_token %} {{form.as_p}} <input class="btn btn-primary" type="submit" name="" value="SUBMIT"> </form> <table id="gallery" class="table table-bordered"> <thead> <tr> <th>Documents</th> </tr> </thead> <tbody> {% for document in documents %} <tr> <td><a href="{{ document.file.url }}">{{ document.file.name }}</a></td> </tr> {% endfor %} </tbody> </table> -
How to retrieve value from queryset in django?
I am trying to retrieve different .values() from query sets but am having an issue with it returning the proper values. How to write my model so that I can retrieve attributes using the .values() method? I have tried to change the model's __str__ method to return a dictionary but that does not work or I am doing it wrong. class Settings(models.Model): bb_bonus_qualify = models.CharField(max_length=16, default=38.00) service_breakpoint = models.CharField(max_length=16, default=1700.00) def __str__(self): return '%s: %s, %s: %s' % ( 'bb_bonus', self.bb_bonus_qualify, 'service_breakpoint', self.service_breakpoint) I would like to say Settings.objects.last().values('bb_bonus') and be returned the value which is self.bb_bonus_qualify. The common error I seem to get is: AttributeError: 'Settings' object has no attribute 'values' -
Manual Django Form Display
I want to manually render the form in my template, but what I'm trying is not yielding the expected result, and it is not apparent as to why. class MyForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['field1'] = forms.BooleanField() self.fields['field2'] = forms.BooleanField() systems = System.objects.all() for i in range(len(systems)): self.fields['s' + str(i)] = forms.BooleanField() self.fields['field3'] = forms.BooleanField() self.initial_fields = [self.fields['field1'], self.fields['field2']] now when I do this in my template: {% for field in form.visible_fields %} {{ field }} {% endfor %} it returns what you would expect...after looking up the method visible_fields it simply returns a list of fields. So in theory, if I create my own list of fields as with self.initial_fields, the form generator should render the following same as above: {% for field in form.initial_fields %} {{ field }} {% endfor %} but instead I get this output in my template: <django.forms.fields.BooleanField object at 0x000001242F51E588> <django.forms.fields.CharField object at 0x000001242F51E400> I'm assuming I'm missing some initialization of the field itself? I don't understand why one works and the other doesn't. Anyone know? -
Authentication in django for both web and mobile
I have django website running with django-allauth authentication. Now, I am planning to build a mobile app using already existing django as a backend. If there is a way I can continue using django-allauth as authentication for mobile app ? What is the standard way to implement authentication in django for both web and mobile ? -
Does django logs user in when register without authenticate() and login() function?
I am practicing django user registration using UserCreationForm() and User() class. My froms.py code is. from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class user(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'password1', 'password2') My views.py code for this is. def register(request): if request.method == 'POST': form = forms.user(request.POST) if form.is_valid(): form.save(commit=False) form.email = form.cleaned_data.get('email') form.save() #context = {'form':form, 'er':form.errors} return redirect('register') else: form = forms.user() context = {'form':form, 'er':form.errors} return render(request, 'register/register.html', context) I did not use authenticate() or login() in the registration system. I have three questions. **In case of using same browser. When I register does the user automatically log in and create a session number or does not? If does log in and generate a session value, what happens if registers again with a new value from same browser? Does system delete previous session and generate new session or something else happens. If I have used authenticate() and login(), what would happen if I try to register again? -
String passed through Django is undefined in JavaScript but renders fine
In Django, I am passing an array of strings ['A', 'B', 'C'] to the view and hoping to use these with a JavaScript script I have on the page. However, even though I am able to display the contents in HTML, when I try use them in JavaScript like such: {% for l in labs %} console.log({{ l }}) {% endfor %} I get an error that 'Reference Error A is undefined' which I cannot comprehend. How is it possible if it is undefined when clearly by referencing the value it is infact defined? -
Django. Change filed type UUIDField to CharField
I had in user model field: class User(PermissionsMixin): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) but i need to change this field on class User(PermissionsMixin): id = models.CharField(primary_key=True, unique=True, max_length=32, default=uuid.uuid4, editable=False) I have postgre data base. when i did migrations i had error: File "/home/alex/projects/Test/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DatatypeMismatch: foreign key constraint "users_groups_user_id_f500bee5_fk_users_id" cannot be implemented DETAIL: Key columns "user_id" and "id" are of incompatible types: uuid and character varying. Can you give me some advice, how i can to change field from UUIDField to CharField -
most effective way of collecting click data from web page
I am trying to develop a web interface for a python based controller. Lets simplify it to a row of 5 LEDs. Every single one has a button on the page - pressing button turns diode on for 0.1s. I experiment with JSON files but still can't understand how to manage the data in the quickest way. How should the clicks be registered and sent to server so it is quick and light? -
every page works but only no reverse match at index page
every related page works but only index page gets NoReverseMatch at / Reverse for 'series_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P[^/]+)\/$'] which I really really don't understand. url for every page including series_detail works.... I tried checking if my index.html is wrong but that's the problem because even with blank html page it still gives me the same error. Here's my code( any help would be greatly greatly appreciated) urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='home'), path('<slug>/', views.series_pg, name='series_detail'), path('series/<slug>/', views.season_pg, name='season_detail'), path('series/season/<slug>', views.episode_pg, name='episode_detail'), path('about/', TemplateView.as_view(template_name='about.html'), name='about'), ] if settings.DEBUG: urlpatterns += [ re_path(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), ] def index(request): series = Series.objects.all() episode = Episode.objects.all().order_by("date") content_dict = { 'series':series, 'episode':episode, } return render(request, 'index.html', content_dict) def series_pg(request, slug): series = Series.objects.get(slug=slug) season = Season.objects.filter(series=series).order_by("season_nr") episode = Episode.objects.filter(series=series).order_by("date") content_dict = { 'series':series, 'season':season, 'episode':episode, } return render(request, 'series.html', content_dict) def get_image_path_series(instance, filename): return '/'.join(['']) class Series(models.Model): name = models.CharField(max_length=128, unique=True) genre = models.CharField(max_length=128, default=1) tv_or_movie = models.CharField(max_length=128, default=1) period = models.CharField(max_length=128, default=1) descritpion = models.TextField() slug = models.SlugField(unique=True) image = models.ImageField(upload_to='get_image_path_series', blank=True, null=True) video = EmbedVideoField(blank=True, null=True) def __str__(self): return self.name -
problem with images on a custom 404 page, django
I am trying to make custom 404 page by adding an image to the page. Problem is that image is not displaying on a page. This image is accessible from any other page in each app in DEBUG TRUE or FALSE mode, no difference, except 404 page where it represented as a just an empty frame. Image is placed in app/static/app root. Tried to place it is main static root -no difference. # urls.py handler403 = curry(permission_denied, exception=Exception('Permission Denied'), template_name='errors/403.html') handler404 = curry(page_not_found, exception=Exception('Page not Found'), template_name='errors/404.html') handler 403 and handler 404 works fine, except images failure. # template <!-- templates/errors/404.html --> {% extends "base.html" %} {% block title %} error 404 {% endblock %} {% load static %} {% block content %} <img src="{% static "appname/404.png" %}" alt="404"> {% endblock content %} Problem is only on 404/403 pages. Everywhere else -no problems at all. Tests displays regularly. Question is what should I check in terms of possible pitfalls I possible keeping out of scope ? thanks in advance -
django-import-export 0.7.0 and diff-match-patch not available anymore
Our company uses django 1.11 and python 3.6 . We used and django-import-export==0.7.0 last year in one of the projects. But now I get an error when using django-import-export 0.7.0. It seems like the diff-match-patch is not existing anymore. It is next to impossible to upgrade django to newer version because some part of the project may stop working. Is there any alternative solution? Your help is appreciated. -
Invalid block tag: 'edit_url', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I'm getting this error message from django, and don't understand why. Here I use extra code i know this error comes from that. But i don't know how to solve this. Here i'm assigning id to edit button. Please help me in that. <tbody> {% for business_obj in business_objs %} {% edit_url="127.0.0.1:8000/addedit/"+ business_obj.id %} <tr> <th scope="row">{{ business_obj.id }}</th> <td>{{ business_obj.business_id }}</td> <td>{{ business_obj.business_name }}</td> <td>{{ business_obj.business_phone_number }}</td> <td>{{ business_obj.email }}</td> <td>{{ business_obj.business_type }}</td> <td>{{ business_obj.address }}</td> <td>{{ business_obj.images }}</td> <td><a href="{% edit_url %}"><i class="fas fa-edit" style="color:blue"></i></a></td> <td><a href="{% url 'native:home_addbusiness_delete' %}"><i class="fas fa-trash-alt" style="color:red"></i></a></td> </tr> {% endfor %} </tbody> -
Broken pipe from ('127.0.0.1', 33748) Without no reasone
I'am using that command line [ python manager.py runserver ] and run successfully but all i get Broken pipe from ('127.0.0.1', 33716) without errors that is slow my project . how can i solve that problem ? Thanks In Advance -
Can I use trained ML model in django
How to use trained ML model in django and run the trained ML model using user provided values in a form.