Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirecting on angular page in django makes me log-out when i logged in with user which is not superuser access
<input type="hidden" name="next" value="{{next}}" /> I am changing this input tag's values from "{{next}}" to "dashboard" for redirection <input type="hidden" name="next" value="/dashboard" /> When i am re-direct django after login into django pages or default urls which is created in urls.py it is working fine but if i tried to redirect http://127.0.0.1:8000/dashboard/ its logged me out sometime. Any help will be appreciated. -
Amp with Google Cache won't take Local Timezone
So I'm developing the AMP version of a web in Django. The problem is that when Google Caches my content it takes the timezone of the Google server that caches the content (EDT) and no the local timezone of my users, so they are getting the wrong time. What can I do to solve this? Thanks! -
How to make unique urls in django with url-pattern that uses multiple parameters?
My url is structured in this way: example.com/category/subcategory/name Right now I'm using a DetailView and it detects the url when I write it but it resolves positively to any address that includes the right name because that name is unique so what I need to check is that the name corresponds to the subcategory and this subcategory corresponds to the main category. For example my desired url is: http://example.com/animal/cat/garfield It resolves alright with a 200 code. However, when I write: http://example.com/insect/cat/garfield It also resolves as a 200 instead of a 404. How do I check those parameters in my view? My urls.py path('<str:category>/<str:subcategory>/<str:slug>', views.AnimalDetailView.as_view(), name="animal_detail") My view: class AnimalDetailView(DetailView): model = Animal def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context -
Django 2.1 can't create a user in migration
I'm trying to add a new user and then associate it to a subset of existing records. For example, imagine I have this app model: class Foo(Model): user = model.ForeignKey(User, default=None, on_delete=models.CASCADE) In my migration I have: from django.contrib.auth.models import User def add_user(apps, schema_editor): anon = User.objects.create_user(username='anonymous') anon.save() Foo = apps.get_model('myapp', 'Foo') foo_to_change = Foo.objects.filter(user_id=1) for f in foo_to_change: f.user = anon f.save() When I run this I get this error: ValueError: Cannot assign "<User: anonymous>": "Foo.user" must be a "User" instance. I thought the problem might be that I'm using the User model directly and the docs say not to do this. So I changed the top part to: User = apps.get_model('auth', 'User') anon = User.objects.create_user(username='anonymous') anon.save() Now I get a different error: AttributeError: type object 'User' has no attribute 'normalize_username' What am I doing wrong? How do I add a new user in a data migration? -
Docker + Celery tells me not to run as root, but once I don't, I lack permissions to run
I have a Django (2.1.2) Docker project that I try to include Celery (4.2.1) which will exit 0 in the end due to permission errors. docker-compose.yml ... celery: build: . command: celery worker -A core --workdir /opt/services/web_app/src -l info volumes: - .:/opt/services/web_app/src depends_on: - database1 - redis After i build with 'docker-compose build' and then run 'docker-compose up' I get this error message: celery_1 | /usr/local/lib/python3.7/site-packages/celery/platforms.py:796: celery_1 | RuntimeWarning: You're running the worker with superuser privileges: this celery_1 | is absolutely not recommended! celery_1 | celery_1 | Please specify a different user using the --uid option So.. I didn't even know Docker had "users" so I added this to my 'Dockerfile' at the bottom before expose. ... RUN groupadd -g 999 celery && \ useradd -r -u 999 -g celery celery USER celery EXPOSE 8000 and then updated the 'Dockerfile' with the user: ... celery: build: . command: celery worker -A core --workdir /opt/services/web_app/src -l info --uid=celery volumes: - .:/opt/services/web_app/src depends_on: - database1 - redis and when I run it now I get error message: celery_1 | File "/usr/local/lib/python3.7/site-packages/celery/platforms.py", line 502, celery_1 | in initgroups return os.initgroups(username, gid) celery_1 | PermissionError: [Errno 1] Operation not permitted -
How can I fix Heroku Server Error (500) error?
I recently deployed my app to https://lawyertobehk.herokuapp.com/. All of it was working, until today, when I deployed new changes. Afterwards, I discovered that the https://lawyertobehk.herokuapp.com/firms/ page wasn't working and was throwing a 500 error. Strange thing is, https://lawyertobehk.herokuapp.com/admin/ is working just fine. I've tried rolling back my code to when it was last working, which has not helped. I'm really frustrated about this. Please help!! Thanks so much guys. -
Django + React Native. How to input data into djano from react native?
This is my first time working with react native and django. I am having trouble connecting them. This is what I have currently. I am unsure of what to write in my json_uploadfunc function so that it would input the value, header, description, priority, duration, due, owner into django. Where can I get more information and what should I write into json_uploadfunc? export default class TaskClass extends React.Component { constructor(props){ super(props); this.state = { header: 'TestClassTask', description: '', priority: null, duration: null, due: null, owner: 'http://durian-django-env.nihngkspzc.us-east-1.elasticbeanstalk.com/profile/2/' } }; json_funtion = () => { fetch('http://durian-django-env.nihngkspzc.us-east-1.elasticbeanstalk.com/task/') .then(response => response.json()) .then(data => { var json_array = data[0]; //get the first obj from django var id = json_array.id.toString(); //get the id var url = json_array.url; //get url var header = json_array.header; //get header var priority = json_array.priority.toString(); //get priority var duration = json_array.duration.toString(); //get duration var due = json_array.due.toString(); //get duedate var owner = json_array.owner; //get owner }) .catch(error => console.log(error)); } json_uploadfun = () => { URLpath = http://durian-django-env.nihngkspzc.us-east-1.elasticbeanstalk.com/task/ } } -
How to enable link back to private area of site on publicly cached pages / fix Memcached Errors
Overview: Hi, I recently enabled caching pages in the urlpatterns with memcached for public pages. But I'm getting AttributeError, TypeError and ConnectionResetError in my terminal when I do the following. This problem only started when I enabled Memcached. My goal: I want to be able to give logged in users a quick link back to their private dashboard, from any public page on the site that has already been cached. If anyone knows a better way to implement that functionality, while allowing memcached on public pages, I'd love to know how... Here's my current setup: I have a base.html file that all public / non logged in pages inherit from. This page has a sidebar that basically says Hello, want to MAKE AN ACCOUNT, or go to your DASHBOARD?, and the capital words are links to a page to make an account / test if the current user is authenticated. Here's the function it goes to, and this function is not cached anywhere. def signup(request): form = .... if request.method == 'POST': if form.is_valid(): ... auth.login(request, user) return redirect(reverse('dashboard', args=[request.user.id])) elif request.user.is_authenticated: return redirect(reverse('dashboard', args=[request.user.id])) return render(request, 'accounts_app/signup.html', {'form': form}) I also have a base_logged_in.html for logged in users. Both … -
Adding another class to serializer in Django
I wish to add another class to an existing serializer. I am able to do simple serializers, but this one is rather tricky because the second class I wish to add comes after the serializer's class in the models.py. Anybody with a clever solution? The models.py is as follows: class Pokemon(models.Model): id = models.AutoField(primary_key=True) type = models.OneToOneField(Type, on_delete=models.PROTECT) stat = models.ForeignKey(Stat, on_delete=models.PROTECT, null=True) class Skills(models.Model): id = models.AutoField(primary_key=True) pokemon = models.ForeignKey(Pokemon, on_delete=models.PROTECT) owner = models.ForeignKey(Owner, on_delete=models.PROTECT, related_name='name') and the serializers.py: class PokemonSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Pokemon fields = ('id', 'type', 'stat') The display that I currently have is: { "id": 2228, "type": "http://localhost:8000/type/4628/", "stat": "99", } and the display that I am shooting for is: { "id": 2228, "type": "http://localhost:8000/type/4628/", "stat": "99", "owner": "bob doe" } Thank you very much in advance! -
How do I generate a PDF from data stored in "tei" format in the PostgreSQL database in Python language in Django framework?
I have an application, front end running on Angular and Backend on Django framework. I have PostgreSQL database for the same. I am selling digital items on this website. So once the user purchases the items, then I need to fetch the items from the PostgreSQL, where the data is stored in the format of "tei" and create a pdf to output the same data and then create a weblink for the same, which will then be emailed to the buyer. Can someone please suggest me ways of doing these? If there are any libraries I can use to achieve the same or any tutorials you guys can direct me to? Or any sort of information regarding these would be appreciated. I found few "HTML- PDF" libraries, but I want to maintain the formatting in the document which is specified by the "tei" code. So, I believe I cant use "HTML-PDF" libraries. Apologies if my question is stupid, I am new to this kind of application building. Thanks in advance. -
Converting python list to a specific javascript format
Using Django, I have the following model: class Score(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) month = models.CharField(max_length=255) points = models.FloatField(null=True, blank=True) I have the following data in this table: Team Date Points A Jan 2015 100 A Feb 2015 150 A Mar 2015 200 B Jan 2015 120 B Feb 2015 200 B Mar 2015 300 C Jan 2015 111 C Feb 2015 122 C Mar 2015 133 So, I my view I can run: data = Score.objects.all() This will return a list with all the aforementioned records. So far, so good. However, I want to show this as a graph in javascript. This requires a very specific format. Firstly, I need to get all the x-axis labels separated ("Jan 2015", "Feb 2015", "Mar 2015"), and then I need to group all the scores by team. This is what the final js should look like: <script> var timeXAxis = ["Jan 2015", "Feb 2015", "Mar 2015"] var timeSeries = [ { name: "Team 1", data: [ ["Jan 2015", 100], ["Feb 2015", 150], ["Mar 2015", 200], ] }, { name: "Team 2", data: [ ["Jan 2015", 120], ["Feb 2015", 200], ["Mar 2015", 300], ] }, { name: "Team 3", data: [ ["Jan 2015", … -
Integrating MongoDB with django?
so I have a MongoDB database with data I collected. I want to take this data and send it in as a rest api, however I can't seem to find any engine to run mongodb using django that was made recently and for the current version of django. Does anyone know of such a library or can direct me to a recent django project that integrates Mongo successfully because I can't find any. Thanks in advance. -
django.db.utils.ProgrammingError: relation "dashboard_menugroup" does not exist
I have these models: # coding:utf-8 from django.db import models from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ class MenuGroup(models.Model): name = models.CharField(_('nome'), max_length=30, blank=False, primary_key=True) slug = models.SlugField(_('slug'), blank=True, null=True, db_index=True) class Meta: app_label = 'dashboard' verbose_name = _('gruppo') verbose_name_plural = _('gruppi') ordering = ('name',) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(MenuGroup, self).save(*args, **kwargs) class MenuProduct(models.Model): name = models.CharField(max_length=30) ingredients = models.CharField(max_length=250) price = models.FloatField(null=True, blank=True, default=0.0) group = models.ForeignKey(MenuGroup, on_delete=models.CASCADE) class Meta: app_label = 'dashboard' verbose_name = _('prodotto') verbose_name_plural = _('prodotti') ordering = ('name',) def __str__(self): return self.name class Order(models.Model): price = models.FloatField(null=True, blank=True, default=0.0) date = models.DateTimeField(auto_now=False) status = models.BooleanField(default=False) class Meta: app_label = 'dashboard' verbose_name = _('ordine') verbose_name_plural = _('ordini') ordering = ('date',) def __str__(self): return self.date class OrderHasMenuProduct(models.Model): product = models.ForeignKey(MenuProduct, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) suppose that we want to reset our database and we launch the following commands: $ find . -path "*/migrations/*.py" -not -name "__init__.py" -delete $ find . -path "*/migrations/*.pyc" -delete And the we launch the commands to recreate the schema: $ python manage.py makemigrations And i obtain the follow output: Migrations for 'dashboard': dashboard/migrations/0001_initial.py - Create model MenuGroup - Create … -
Cannot deply django api with heroku
When i try to deploy my django rest api with heroku i get this: -----> Python app detected Using supported version of Python 3.6 (python-3.6.6) -----> Installing python-3.6.6 -----> Installing pip -----> Installing SQLite3 -----> Installing requirements with pip Collecting Python==3.5.1 (from -r /tmp/build_eff222df1413c9c747fe9d073117baf7/requirements.txt (line 1)) Could not find a version that satisfies the requirement Python==3.5.1 (from -r /tmp/build_eff222df1413c9c747fe9d073117baf7/requirements.txt (line 1)) (from versions: ) No matching distribution found for Python==3.5.1 (from -r /tmp/build_eff222df1413c9c747fe9d073117baf7/requirements.txt (line 1)) ! Push rejected, failed to compile Python app. ! Push failed How can i set my requermients.txt for this to work?, i used a virtual env, where i installed this: django djangorestframework django-rest-auth django-filter django-cors-headers im using python 3.5, and django 2.0.1 -
Unable to create a django project
C:\Windows\System32>django-admin.py starproject wisdompets Unable to create process using 'c:\program files\python36\python.exe "C:\Program Files\Python36\Scripts\django-admin.py" starproject wisdompets' -
Django Rest Framework Custom Permission's Message Not Shown
I'm writing an application with the Django Rest Framework. I created a custom permission. I provided a message attribute to the custom permission, but still the default detail gets returned. Let me give you my code. permissions.py: from annoying.functions import get_object_or_None from rest_framework import permissions from intquestions.models import IntQuestion from ..models import Candidate, CandidatePickedIntChoice CANDIDATE_ALREADY_ANSWERED = "This candidate already answered all questions." class CandidateAnsweredQuestionsPermission(permissions.BasePermission): """ Permission to check if the candidate has answered all questions. Expects candidate's email or UUID in the request's body. """ message = CANDIDATE_ALREADY_ANSWERED def has_permission(self, request, view): candidate = None email = request.data.get("email", None) if email: candidate = get_object_or_None(Candidate, email=email) else: uuid = request.data.get("candidate", None) if uuid: candidate = get_object_or_None(Candidate, uuid=uuid) if candidate: picked_choices = CandidatePickedIntChoice.objects.filter( candidate=candidate ).count() total_int_questions = IntQuestion.objects.count() if picked_choices >= total_int_questions: return False return True views.py: from annoying.functions import get_object_or_None from rest_framework import generics, status from rest_framework.response import Response from ..models import Candidate, CandidatePickedIntChoice from .permissions import CandidateAnsweredQuestionsPermission from .serializers import CandidateSerializer class CandidateCreateAPIView(generics.CreateAPIView): serializer_class = CandidateSerializer queryset = Candidate.objects.all() permission_classes = (CandidateAnsweredQuestionsPermission,) def create(self, request, *args, **kwargs): candidate = get_object_or_None(Candidate, email=request.data.get("email", None)) if not candidate: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) else: serializer = … -
How to send a file from Django backend to server
I am sending an ajax request with a file to my backend that processes it. After processing it into another form (image into a compressed processed directory), I want to send that back to the user to down load that. Can someone provide an example view that will, when it receives the file, process the data the send a request that has the file. Also, please show me how to download that file in the javascript front end. class send_text: def post(self, request): file = request.POST["file"] # Processing…………… file_to_send = <path to file> # show how to send the file here Also the frond end: $.ajax{ //sending the data onSuccess: //show how to download the data here } Thank you in advance. -
Where are Django signal errors printed?
After reading two related questions: How do I make Django signal handlers not fail silently when an exception is encountered in the signal handler? How Django signal receiver should handle errors? ... it's apparent that Django signal errors are failing silently. I am wondering, where are the errors sent to? I'm not on production, so it's not using apache. I'm simply testing with python manage.py runserver and nothing is printing in the console when an error occurs. -
Django formset_factory vs modelformset_factory vs inlineformset_factory
Forms can be complicated in Django. Formsets can make you want to quit Django. I'm at that point. What are the different use cases and considerations of which one(s) to use? I'm looking for some better guidance as to when to use each factory, as they seem to depend on when you know what type of form, fields, and whether or not you are creating, editing, or deleting (individual forms entirely or the parent model altogether). Below are some pseudo code with assumptions/restrictions to help you help me understand the differences. It may help to provide psuedocode, such as what kind of Form (ModelForm or regular) goes with the Formset, or what should be popped from the form, given this seems to be a trend for creating forms with relations. Assuming you have some models: class Dish(models.Model): name = models.CharField(max_length=50) class Meal(models.Model): name = models.CharField(max_length=50) dishes = models.ManyToManyField(Dish, # through='OPTIIONALMealDishIntermediaryClassTable', related_name="meal") class Reservation(models.Model): date = models.DateTimeField() greeting = models.CharField(max_length=255) meal = models.OneToOneField(Meal, on_delete=models.CASCADE) class MealPhotos(models.Model): photo = models.OneToOneField(Photo, on_delete=models.CASCADE, related_name='mealPhoto') meal = models.ForeignKey(Meal, on_delete=models.CASCADE) # optional, so a photo can be attached to a dish if the picture is just of the dish dish = models.ForeignKey(Dish, blank=True, null=True, on_delete=models.CASCADE) And … -
How can I use my modelForm field inside of a bootstrap form field?
my forms.py look like this class UserRegistration(UserCreationForm): def __int__(self, *args, **kwargs): super(UserRegistration, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-registrationForm' self.helper.form_class = 'u-form--modern' self.helper.form_method = 'post' self.helper.form_action = 'submit_form' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = User fields = ['first_name', 'username', 'last_name', 'email', 'password1', 'password2'] and my templates look like this( i display only 1 field cuz they are more or less similar) <form class="js-validate mt-5" id="id-registrationForm" method="post"> <div class="js-form-message mb-4"> <label class="h6 small d-block text-uppercase "> Email address</label> <div class="js-focus-state input-group u-form"> <input type="email" class="form-control u-form__input" name="email" placeholder="your@email.com"> </div> </div> Unfortunately my front-end skills are close to 0 and I could not really find out how to use my {{ form.email }} inside of a bootstrap's premade form. I need this to submit my modelForm and register a user. Just to make it clear, i want my django form look like the one on the bottom -
Content Security Policy blocks Data
My content security policy IMG-SRC keeps blocking images 'data:image/png;base64...' and I don't know where they are coming from. I use report-uri to manage my CSP reports, and it allows you to ignore any reports beginning with 'data:...', but it says "Only enable this filter if you are sure you understand what this means." Can anyone help me understand what this means, and where these data images would be coming from? -
FileNotFoundError: WinError 2 The system cannot find the file specified:
The question is a continuation of this: Bulk download of images rendered under mulitple categories in a single html page I am getting the following error when I click on any of the download buttons: [WinError 2] The system cannot find the file specified: 'name of the first image file in the queryset' even though the path is correct. Please help me out. -
in Django variables value does not appear in HTML link
I have 3 drop down menus. each menu takes it's values through variable passed through object context. here is the view function: def home_page(request): template = 'path/to/template.html' cities = City.objects.all() all_categories = Category.objects.all() all_sub_category = Sub_Category.objects.all() context={ 'cities': cities, 'all_categories': all_categories, 'all_sub_category': all_sub_category, } return render(request, template, context) the template is as follow: {% load staticfiles %} <select> {% for city in cities %} <option value='{{city.city_name}}'> {{city.city_name}} </option> {% endfor %} </select> <select> {% for category in all_categories %} <option value='{{category.category_name}}'> {{category.category_name}} </option> {% endfor %} </select> <select> {% for sub_category in all_sub_category %} <option value='{{sub_category.sub_category_name}}' > {{sub_category.sub_category_name }} </option> {% endfor %} </select> <a href="http://domain_name/towns/{{city.city_name}}/{{category.category_name}}/{{sub_category.sub_category_name}}"><span > move to next page </span> </a> the problem is that the resultant URL is missing all three variables even though all variables are displayed in the drop down menus. here is the resultant link: http://127.0.0.1:8000/towns/// I tried also the following href: href="http://domain_name/towns/{{city.city_name.0}}/{{category.category_name.0}}/{{sub_category.sub_category_name.0}}"><span > move to next page </span> </a> any help or suggestion? -
"Reverse for ... not found" - but there is?
Ok, I've been banging my head against this for 30+ minutes, so here I am on stack overflow. I've got in a template: {% if user.is_authenticated %} <a href="{% url 'admin' %}"> Admin </a> {% endif %} And in urls.py: urlpatterns = [ path('admin', admin.site.urls, name = 'admin'), path('', views.index, name ='index'), ] Yet I still get: NoReverseMatch at / Reverse for 'admin' not found. 'admin' is not a valid view function or pattern name. Why is that? I even tested it out, and replaced admin with index, and it redirects me to views.index. I tried replacing the name of the pattern with everything else and tried matching it with the url path as well (like it is now). No luck! Did I just break django? -
.pyc extention Django
I was reading that .pyc contain byte code, which is what the Python interpreter compiles the source to. This code is then executed by Python's virtual machine. Hoever, since I'm learning Django for the first time and coming from Node.js it's a little different, everytime I type on my terminal python manage.py runserver it creates multiple versions of the same file but in .pyc format, which by the definition I'm guessing that's the compiled version so it's faster, but I think it's too many files, is that normal? What if don't want to compile it to have all those extra files? I'm learning python and Django for the first time, could someone clarify this a little please. Here is a picture of what I mean with the extra files: Also in the tutorial that I' following they have from django.conf.urls import path, and the new version of Django has from django.conf.urls import url, just want to make sure, they are the same right? Thank you