Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JsonResponse data isn't sent to template
i'm learning to use ajax with django this is the resault {"post": "[{\"model\": \"app.post\", \"pk\": 37, \"fields\": {\"author\": 2, \"updated_dt\": \"2021-04-27T14:22:07.811Z\", \"content\": \"Second Post\", \"created_dt\": \"2021-04-27T14:22:07.677Z\", \"status\": 0, \"page\": null, \"group\": null, \"photo\": \"\", \"video\": \"\", \"likes\": [], \"love\": [], \"sad\": [], \"wow\": [], \"haha\": [], \"angry\": []}}]"} i don't know what seems to be the problem that's my views : def AddPostView(request): content = request.POST.get('content') pic = request.FILES.get('photo') vid = request.FILES.get('video') author = request.user post = Post.objects.create(author=author, photo=pic, video=vid, content=content) post.save() name = request.user.first_name.capitalize() + " " + request.user.last_name.capitalize() data = serializers.serialize('json', [ post, ]) return JsonResponse({"post": data}, status=200) that's the ajax code url = '{% url 'add-post' %}' $("#posts-submit").click(function () { $.ajaxSetup({ headers: { "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value, } }); $.ajax({ url: url, method: 'POST', dataType: 'json', success: function (data) { $("#posts-container").appendToUsrTable(data.html_form); } }); }); -
Django: Try reverse of model's __str__() function
I want a function that can have the reverse result of the model __str__ function. For example I have: Model class DepartmentModel(models.Model): department_name = models.CharField(max_length=100) department_description = models.CharField(max_length=500) def __str__(self): return self.department_name As part of the Custom Field TypedModelListField I need to convert the models string representation into an object if it exists. Say I have object <DepartmentModel: Finance> which called __str__() returns "Finance" I'd like to take string "Finance" and have the effects of reversing the __str__() function to return the object <DepartmentModel: Finance> if possible. Form class AddDepartment(forms.Form): user = CustomFields.TypedModelListField( queryset=DepartmentModel.objects.all()) Custom Field class TypedModelListField(forms.ModelChoiceField): def to_python(self, value): if value == '' or value == None: raise forms.ValidationError('Entry cannot be empty') ##################################################################### ### HERE I WANT TO TRY AND CONVERT __STR__ REPRESENTATION to OBJ ### ##################################################################### value = super().to_python(value) return value class ListTextWidget(forms.TextInput): def __init__(self, dataset, name, *args, **kwargs): super().__init__(*args) self._name = name self._list = dataset self.attrs.update({'list':'list__%s' % self._name,'style': 'width:100px;'}) if 'width' in kwargs: width = kwargs['width'] self.attrs.update({'style': 'width:{}px;'.format(width)}) if 'identifier' in kwargs: self.attrs.update({'id':kwargs['identifier']}) def render(self, name, value, attrs=None, renderer=None): text_html = super().render(name, value, attrs=attrs) data_list = '<datalist id="list__%s">' % self._name for item in self._list: data_list += '<option value="%s">' % item data_list += '</datalist>' return (text_html + … -
IntegrityError at /job/create/ NOT NULL constraint failed: core_job.category_id
I'm creaating an api that user can create a job. when I want to test it with postman and create a job I have this error: IntegrityError at /job/create/ NOT NULL constraint failed: core_job.category_id how do i can fix it ?? models: class Category(models.Model): name = models.CharField(max_length=300) slug = models.SlugField(max_length=300, unique=True, help_text='write in English.') sub_category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) class Job(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=400, unique=True) slug = models.SlugField(max_length=400, unique=True, allow_unicode=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True) description = models.TextField(null=True, blank=True) phone1 = models.CharField(max_length=12, null=True, blank=True) phone2 = models.CharField(max_length=12, null=True, blank=True) phase = models.CharField(max_length=1, null=True, blank=True) address = models.TextField(null=True, blank=True) daily_start_work_time = models.TimeField(null=True, blank=True) daily_end_work_time = models.TimeField(null=True, blank=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) popular = models.BooleanField(default=False) views: class JobCreateView(generics.CreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = JobSerializer queryset = Job.objects.all() -
Django development server restarts when changing template (HTML) files
I started a new project in Django 3.2. Unlike what I am used to, on my development machine the runserver restarts automatically when I change template files (HTML files). I am not used to this happening - normally these would always be loaded from disk and changes did not require a restart. A restart is fast but not instantaneous and I rather have the old behavior. I checked the changelog and the runserver documentation but I am not sure if this really is a recent change, or a setting, or if I am overlooking something. Anyone any idea? Below the output of the server in my docker container where you can see that a change to an HTML file triggers the restart... web_1 | /src/templates/_nav.html changed, reloading. web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | April 27, 2021 - 14:16:17 web_1 | Django version 3.2, using settings 'demo.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. -
What is views.py for?
I am currently learning how to build a backend and I have not once stumbled upon the views.py file. Almost everything is happening in my models.py or admin.py file. Is that a problem? What even is views.py for? -
How to user Supervisord with django-background-task module
I am running several background process using django-background-tasks module https://django-background-tasks.readthedocs.io/en/latest/.I am using nohup command for running these 3 queues. can anyone tell me me exactly how to setup http://supervisord.org/ in django to run these background tasks. Thanks in advance. @background(queue='bcp') def process1(): ........ @background(queue='acp') def process2(): ........ @background(queue='fcp') def process3(): ........ -
Dynamically adding cron task on digitalocean with django
I am trying to add a cronjob on DigitalOcean, I've set up Cron by following this tutorial I want to add my cron task lines through Django code, something like file_object = open('/tmp/crontab.UmBDmC/crontab', 'a') file_object.write('* * * * * curl https://mydomain/someurl/') file_object.close() But I can't locate the crontab.UmBDmC folder, every time I run crontab -e I get a different folder name containing crontab file How can I add and remove lines from this file programatically? Any help would be appreciated. -
Django formsets vs writable nested serializers of REST API + JS Framework
I am learning Django since 5 months and I came to a situation where I have to decide if continue learning: Either go in deep with the django formsets (https://docs.djangoproject.com/en/3.1/topics/forms/formsets/) Or start with writable nested serializers of REST API + JS Framework (Angular, I like they wy it is organized). (https://www.django-rest-framework.org/api-guide/relations/#nested-relationships) What do you guys think it is more robust? I suppose the second one but maybe you have more to tell. Thank you very much :) -
Field 'id' expected a number but got <Salary: : - Claude maniragaba>
I want to enable edit when hr state of change is approved def has_change_permission(self, request, obj=None): salary = Salary.objects.filter(id=obj).first() if obj.hr_state == 'request-change-approved' and request.user.user_role.position.code == 'HRM': return True else: return False -
Will there be any style changes when we run a Django project with localhost:8000 and 127.0.0.1:8000?
I tried running server using localhost:8000 and 127.0.0.1:8000 and I noticed that font size is different in both. I couldn't figure out the reason .Fontsize Difference -
how to convert the sql statement to annotate statement
SELECT substr(json_extract(f_test,'$.field_summary.age'), instr(json_extract(f_test,'$.field_summary.age'),'->')+5) AS summary FROM table name; How can I add the sql statement in the objects.annotate(sql)? I succeeded in getting the desired result value with the sql statement, but now this conditional statement is needed for filtering on the object. It is not a simple phrase (ex: select * from school;), but I will contact you I could not find it by googling -
how many fields can be in a django model?
I see some issues in my database while updating my model in Django. it only shows 12 fields! when I added one more field to it and then run makemigrations command, it does not show any changes. I'm using MySQL database init. is there anything in the Django model like we can only define some fields or we can define as much as we need? -
TemplateDoesNotExist at /messages/inbox/ pinax/messages/inbox.html
The Template is present but somehow it wont get located. What could be the problem? -
Django Google AllAuth Site matching query does not exist error on login
I have a Django app I'm trying to deploy on Heroku. Currently, it is deployed to csproject-justin.herokuapp.com . You can find the entire code at https://github.com/travelingaries/Django-Simple-Reservation-App The problem is, when I click on the login button at the top right corner and then press 'Sign in with Google', it throws DoesNotExist at /accounts/google/login/ SocialApp matching query does not exist. I've tried measures suggested on other StackOverflow threads, but none seems to work. When I try to change the Site_ID, it throws an error on the page that shows the Google Sign In button instead(it says 'DoesNotExist at /accounts/login'), so I'm not sure which one's correct. If anyone can help with this issue, I'd greatly appreciate it! Thanks in advance -
Filter Products by category when category page loads angular
I have a angular webapp that displays all the categories from the category model. The category model is a foreign key the products model. I want to be able to filter and view all the products that has that category when I click and load that specific category view. When I click on a category at the minute it takes me to a details page where I can see the category name, image and description. I can also see all of the products in my DB within that details view. I want to filter these so that only the products that contain that specific category in its foreign key field will be shown in the category details view rather than all of the products. If anyone could help me out here it would be greatly appreciated! Here is what I have so far: department.component.ts import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CookieService } from 'ngx-cookie-service'; import { ApiService } from 'src/app/api.service'; import { Category } from '../../models/Category'; import { Product } from '../../models/Product'; @Component({ selector: 'app-department', templateUrl: './department.component.html', styleUrls: ['./department.component.css'] }) export class DepartmentComponent implements OnInit { categories: Category[] = []; … -
NGINX HTTP 499s with AWS NLB & Gunicorn _ Django
I am running a NGINX + Gunicorn setup to serve my Django app from AWS EC2s, which have a Network Load Balancer on the front. Recently I have been getting a lot of HTTP 499s from my NGINX, all of them continuous and not a one-off. AWS Network Load Balancers have a fixed idle timeout of 350s, which cannot be modified I believe. All my NGINX timeouts are set at 600. What else can be the reason for this? Below is my NGINX config user <someuser>; worker_processes auto; error_log /var/log/<somedir>/nginx_error_main.log; pid /var/run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/<somedir>/nginx_access_main.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 600; types_hash_max_size 2048; proxy_ignore_client_abort on; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; index index.html index.htm; # Enable upgrading of connection (and websocket proxying) depending on the # presence of the upgrade field in the client request header map $http_upgrade $connection_upgrade { default upgrade; '' close; } # Create an upstream alias to where we've set daphne to bind to upstream … -
Django login problem which is being linked with the admin side
I am working on a Django project and have implemented login and logout functionalities. The project is a job portal. When I login as a recruiter, previously I was able to open another tab in my browser and use the django admin panel. Now, whenever I do that, it says that I am logged in as my recruiter email address and I have to log in using another account. Now, when I log in using my admin credentials, simultaneously, I am being logged in on my website using my admin credentials which I have never registered on the site. Why am i getting this??? Thank you for your reply guys. This has impeded my work progress since hours -
How can i put the commas for urls when i need 3 differents on javascript?
How can i put the commas? Hello im trying to insert a image with a JavaScript append funtion. Loading the static folder from Django and i cant quotation the url imagen (needed where are ##) because im using '' to delimiter the line of js and "" to delimiter src="" tag for html: '<a href="#" class=""><img src="{% static ##images/img_1.jpg## %}" alt="Image" class="img-fluid coche-img"></a>' What can i do? Can i put 3 different commas? -
How do I restrict access in django?
I have an application in which all users, after registration, can publish articles, how can I make it so that only those who have the rights for this can publish (something like ordinary users and moderators / editors and how to grant these rights. Below is the attached code: models.py/blogapp class Post(models.Model): title = models.CharField(verbose_name=("Заголовок"), max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) header_image = models.ImageField(verbose_name=("Заглавное Изображение"), null=True, blank=True, upload_to="images/" ) body = RichTextField(verbose_name=("Тело Статьи"), blank=True, null=True) #body = models.TextField(blank=True, null=True) post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(verbose_name=("Категория"), max_length=200) snippet = models.CharField(verbose_name=("Фрагмент Статьи"), max_length=200) likes = models.ManyToManyField(User, related_name='blog_post') updated_on = models.DateTimeField(auto_now= True) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) views.py/members class CreateProfilePageView(CreateView): model = Profile form_class = ProfilePageForm template_name = "registration/create_user_profile.html" #fields = '__all__' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class EditProfilePageView(generic.UpdateView): model = Profile template_name = 'registration/edit_profile_page.html' fields = ['bio', 'profile_pic', 'website_url', 'instagram_url', 'twitter_url', 'status', 'age'] success_url = reverse_lazy('home') class ShowProfilePageView(DetailView): model = Profile template_name = 'registration/user_profile.html' def get_context_data(self, *args, **kwargs): #users = Profile.objects.all() context = super(ShowProfilePageView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(Profile, id=self.kwargs['pk']) context["page_user"] = page_user return context class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangingForm #form_class = PasswordChangeForm success_url = reverse_lazy('password_success') … -
How to migrate MyIsam to InnoDB with relation (Foreign key constraint is incorrectly formed)?
Previously, the attribute_values table had an int attribute_id field. I want to convert it to a ForeignKey to the attributes table, but I get the error "Foreign key constraint is incorrectly formed" (also the tables used to be MyIsam, I converted them to InnoDB). The migration looks like this: operations = [ migrations.RemoveField( model_name='attributevalue', name='attribute_id', ), migrations.AddField( model_name='attributevalue', name='attribute', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='attributes.attribute'), ), ] atrributes attribute_values -
Building elasticsearch indexes from another container
I have a Django project that uses django-elasticsearch-dsl. The project is dockerized, so elasticsearch and the web projects leave in separate containers. Now my goal is to recreate and repopulate the indices running python manage.py search_index --rebuild In order to do that, I try to run the command from the container of the web service the following way: docker-compose exec web /bin/bash > python manage.py search_index --rebuild Not surprsiginly, I get an error Failed to establish a new connection: [Errno 111] Connection refused) apparently because python tried to connect to elasticsearch using localhost:9200. So the question is, how do I tell the management command the host where elasticsearch lives ? Here's my docker-compose.yml file: version: '2' services: web: build: . restart: "no" command: ["python3", "manage.py", "runserver", "0.0.0.0:8000"] env_file: &envfile - .env environment: - DEBUG=True ports: - "${DJANGO_PORT}:8000" networks: - deploy_network depends_on: - elasticsearch - db elasticsearch: image: 'elasticsearch:2.4.6' ports: - "9200:9200" - "9300:9300" networks: - deploy_network db: image: "postgres" container_name: "postgres" restart: "no" env_file: *envfile ports: - "5432:5432" volumes: - db_data:/var/lib/postgresql/data volumes: db_data: networks: deploy_network: driver: bridge UPDATE: In the Django project's settings I setup the elasticsearch dsl host: # settings.py ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' } } -
(M1 Mac) Geodjango GDAL: mach-o, but wrong architecture
I am trying to get GeoDjango running on mac os and have hit a problem with GDAL. I have downloaded and installed GDAL without problem (Gdal Complete Binary) also installed from homebrew too. Unfortunately when i was installed gdal with homebrew django can't find the gdal and throws gdal did not find error, after that. I installed from KyngChaos GeoDjango Binary django find gdal but now throws that; OSError: dlopen(/Library/Frameworks/gdal.framework/gdal, 6): no suitable image found. Did find: /Library/Frameworks/gdal.framework/gdal: mach-o, but wrong architecture /Library/Frameworks/gdal.framework/gdal: mach-o, but wrong architecture /Library/Frameworks/GDAL.framework/Versions/3.1/GDAL: mach-o, but wrong architecture /Library/Frameworks/GDAL.framework/Versions/3.1/GDAL: mach-o, but wrong architecture I think the Kyngchaos build not compaitable with arm platform Any help would be much appreciated. Django Version : 3.0 also tried 3.2 Gdal Version : 3.2/3.1/2.4 All of them tried Python Version: 3.8 Postgresql Version : 13 Postgis/Geos installed gdal-config --libs: -L/opt/homebrew/Cellar/gdal/3.2.2_3/lib -lgdal -
Error while executing Pylint command from terminal on Django Project directory
When i run the below command from my terminal i end up getting the below error, i am running this pylint on my django-project. (venv) mypc:~/path/django-project$ pylint --rcfile=.pylintrc ./* > lint_ouput.txt Error: Traceback (most recent call last): File "/usr/lib/python3.6/tokenize.py", line 390, in find_cookie line_string = line.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfa in position 9: invalid start byte pylint.exceptions.InvalidMessageError: Message E0001 must provide line, got None -
Will a class work good without being a model in Django?
I'm currently developing an app which requires simple otp authentication using django In models.py of an app accounts I've created a class to store the otp without making it as a model as follows, class temp: def __init__(self,otp): self.otp = otp print(self.otp) In views.py the code goes as, g = globals() ... some code g["user"+ str(request.POST['username'])] = models.temp(the_otp) This works completely fine in localhost, Will this work if I deploy this to heroku. If not suggest some other way to store the otp temporarily without making models. Thanks in advance. -
django_migrations outputs ORA-02000: missing ALWAYS keyword?
when i try to run python manage.py migrate command i get the following error raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-02000: missing ALWAYS keyword) Note: I can read and write to oracle database nd using pycharm IDE. Thanks.