Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker exec django tests causing memory issue in github actions
I have three docker containers, python for django, node for react, and postgres as the database. I'm running all of these using docker-compose for local development. When I push changes to github I want github actions to build my containers and run the django tests. The code that I wrote works locally but when running it using github actions, the docker exec command is causing Error: Process completed with exit code 137.. Any help with fixing this would be appreciated. Here is the code for the compose file: services: django: hostname: django container_name: django build: context: ./backend dockerfile: dev.Dockerfile ports: - 8000:8000 volumes: - ./backend:/backend environment: - SECRET_KEY=development_secret - DEBUG=1 - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} depends_on: db: condition: service_healthy networks: - backend command: > bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" nodejs: build: context: ./frontend dockerfile: Dockerfile ports: - 3000:3000 volumes: - ./frontend:/app depends_on: db: condition: service_healthy networks: - backend db: image: postgres ports: - 5432:5432 environment: - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} networks: - backend healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"] interval: 5s timeout: 5s retries: 5 networks: backend: name: colgate_network driver: bridge For the github actions file: name: Django CI on: push: … -
Trying to Run Celery Tasks on Remote Server
I have been scouring the Internet for some sort of guide for setting up django, celery, and redis so the celery task runs on a remote server, and I cannot seem to find out how to do this. I have three machines - tsunami (development), trout (production), and t-rex (Nvidia card). I am running some image manipulation algorithms using celery and redis. I have the same django/celery code base on all three computers. When I run the algorithms on tsunami or trout without CUDA support, it takes hours to complete. When I run the same algorithms on t-rex with CUDA support, they complete in minutes. What I would like to do is offload the celery tasks from trout and tsunami to t-rex, and return the results to the either trout or tsunami. By results, I mean a file to save on the local file system or data added to the local mysql (8.0.32) database. Is this even possible? Can someone point me to a guide on how to set this up? I am running django 4.1.7, celery 5.2.7 and redis server 6.0.16. Trout and tsunami are running Ubuntu 20.04, and t-rex is Ubuntu 22.04. All are running Python 3.8. I … -
How to interact with heroku connect Salesforce data in a Django app
I'm new to heroku connect with Django, although I've used heroku connect with other stacks. Are models that inherit from hc_models.HerokuConnectModel supposed to create database tables? I have a django project set up like so (abbreviated for readability) ├── app │ ├── __init__.py │ ├── common │ │ ├── __init__.py │ │ ├── apps.py │ │ ├── favicon_urls.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── urls.py │ │ └── views.py │ ├── core │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── factories.py │ │ ├── forms.py │ │ ├── management │ │ │ ├── __init__.py │ │ │ └── commands │ │ │ ├── __init__.py │ │ │ └── create_test_data.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ └── __init__.py │ │ ├── models.py ....... │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt ├── runserver.sh ├── salesforce_company │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py I have all mappings set up with heroku connect on the heroku web GUI. I have … -
React component NOT updating by itself after change in data without refreshing the entire page
I am using ReactJS on the front-end to make a POST request to my Djando API. After I make the POST request, I expect for my React component to update itself without me having to refresh the entire page. I'm using a useEffect hook to call the my endpoint(GET) to retrieve the data I just updated. import React from 'react' import CampaignList from '../components/CampaignList' import {useState, useEffect} from 'react' const campaignRequest = () => { fetch('http://localhost:8000/api/v1/campaigns/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email_address: "zztop1111122233344556677889910101010@gmail.com", first_name: "i", last_name: "k", stage: "1" }) }) .then(res => res.json()) .then(data => console.log(data)) .catch(error => console.log(error)) } let Campaigns = () => { const [recipients, setRecipients] = useState([]); const [isLoading, setIsLoading] = useState(true); console.log("Campaign is re-mounted") useEffect(() => { setIsLoading(true); fetch('http://localhost:8000/api/v1/campaigns/') .then((res) => res.json()) .then((data) => { setRecipients(data); setIsLoading(false); }) .catch(error => console.log(error)); // fetchData() } ,[]); if (isLoading) { return <p>Loading...</p>; } return ( <div> <div>Campaigns</div> <CampaignList recipientss={recipients}/> {/* <div> {recipients.map((recipient, index) => ( <h3 key={index}>{recipient.email_address} </h3> ))} </div> */} <button onClick={campaignRequest}>Click Me</button> </div> ) } export default Campaigns -
as_crispy_field filter does not render the model's validation errors
views.py: class LoadRequestView(BSModalFormView): template_name = 'sales_portal/activation_request.html' body_template_name = 'sales_portal/activation_request_body.html' form_class = ActivationRequestForm #model = ActivationRecord def form_valid(self, form, **kwargs): form_instance = form.instance invoice_id = self.kwargs.get("invoice_id") invoice = get_object_or_404(InvoiceRecord, pk=invoice_id) # add the host information to the invoice host_information, created = HostInformation.objects.get_or_create( host_id = form_instance.host_id, host_method = form_instance.host_method, host_ref = form_instance.host_ref ) host_information.save() invoice.hosts.add(host_information) # update the activation record with the host information for activation_record_id in form.cleaned_data.get("activations", []): activation = get_object_or_404(ActivationRecord, pk=activation_record_id) activation.host_method = host_information.host_method activation.host_id = host_information.host_id activation.host_ref = host_information.host_ref activation.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): id = self.request.POST.get('id') data = { 'request_form':form, 'id':id, 'submit_url':reverse_lazy('load_request', kwargs={'id':id}) } activations = ActivationRecord.objects.filter(purchase_order=id, host_id=None) # check for host_id null too table = RequestActivationsTable(activations) RequestConfig(self.request).configure(table) data['table'] = table print(f"the form errors are {form.errors}") return HttpResponse(render(self.request, self.body_template_name, data),status=400) forms.py: class ActivationRequestForm(BSModalModelForm): encoded_activation_request = forms.CharField(required=True, label="Activation Request", widget=TextInput(attrs={"onkeydown":"return false;"}) ) def __init__(self, *args, **kwargs): if 'request' in kwargs : request = kwargs.pop('request') super(ActivationRequestForm, self).__init__(*args, **kwargs) #self.helper = FormHelper() #self.helper.error_text_inline = False #self.helper.form_method = 'post' self.fields.update({ 'activations': RequestedProductChoiceField( widget=HiddenInput(), required=False, label='Products' ), }) self.fields["host_ref"].label = "Customer Reference" self.fields["host_method"].label = "Host Verification Method" class Meta: model = ActivationRecord #fields = '__all__' fields = ("encoded_activation_request","host_id", "host_method", "host_ref", "feature_name") widgets = { "host_id": TextInput(attrs={"readonly": "readonly"}), "host_method": TextInput(attrs={"readonly": "readonly"}), "host_ref": TextInput(attrs={"readonly": … -
Getting images to display correctly in a django view
I have a view inside my django app called flashcard_view which displays some images. There is a small problem with how the images are displayed. The problem is that the overlay images are slightly offset or running of the edges of the images underneath them. This is what I see: Here is the code for this template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <link rel="stylesheet" href="{% static 'am_flashcard_template.css' %}"> </head> <body> <h1>Flashcard Display</h1> {{ flashcard }} {#BEGINNING OF ANKIMASTER TEMPLATE#} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script> <div class="card"> <div class='top'> </div> <div id='sentence-example'>{{flashcard.sentence}}</div> <div class='dictionary-form'>{{flashcard.word_dict_form}}</div> <div class='brown mid-text'>{{flashcard.ipa}}</div> <div class='images-container'> <div> <img src='{{flashcard.image_1_url}}'/> <img class='overlay' src='{{flashcard.image_1_overlay}}'/> </div> <div> <img src='{{flashcard.image_2_url}}'/> <img class='overlay1' src='{{flashcard.image_2_overlay}}'/> </div> <div> <img src='{{flashcard.image_3_url}}'/> <img class='overlay2' src='{{flashcard.image_3_overlay}}'/> </div> <div> <img src='{{flashcard.image_4_url}}'/> <img class='overlay3' src='{{flashcard.image_4_overlay}}'/> </div> <div> <img src='{{flashcard.image_5_url}}'/> <img class='overlay4' src='{{flashcard.image_5_overlay}}'/> </div> </div> <div class='part-of-speech mid-text'>{{flashcard.pos}}</div> <!-- Class mid-text setting font-size on 30 px --> {#<div id='definition'>{{Definition}}</div>#} <div id='word-translation'>{{flashcard.word_trans}}</div> <button class='btn-translation' id='wordtrans'>WORD TRANSLATION</button> </div> <script> /* * We can select element by tag $('tagname'), by class name $('.classname') or by id $('#id'). * If an error occurs while loading an image, such as a broken link, we hide that image with = $(this).hide(). * … -
About join 2 modules and show all in Django
I try to join 2 modules and show parts data of them on homepage, yes, I have data already, and below is my files. class Products(models.Model): products_id = models.AutoField(primary_key=True) products_type = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'wdb_products' class ProductsDescription(models.Model): products_id = models.ForeignKey(Products, null=True, on_delete=models.SET_NULL, related_name='pdtion', db_constraint=False) class Meta: managed = False db_table = 'wdb_products_description' # view.py from django.shortcuts import render # from .models import WdbProducts, WdbProductsDescription from .models import ProductsDescription, Products def index(request): products = Products.objects.select_related('pdtion').filter(products_type=1) return render(request, 'product/MainProduct.html', {'products': products}) but those don't work, the data of WdbProductsDescription is empty, actually I can got all of them data thru sql script. can you tell me what's wrong on it? -
Trouble connecting django (container on ec2) to a postgresql database (container) running on a remote server
So here is the setup: 1. I have a django container, postgresql container, and an nginx proxy running on an ec2 instance 2. I have another postgresql container running on locally on an ubuntu server 3. I am trying to connect the django server to the local postgresql server just to read data Configuration: 1. for django I have the configuration for the remote database 2. Here is the config. All variables are set in a .env file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS') }, 'nlp_data': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('NLP_DB_HOST'), 'NAME': os.environ.get('NLP_DB_NAME'), 'USER': os.environ.get('NLP_DB_USER'), 'PASSWORD': os.environ.get('NLP_DB_PASS') } } Problems: 1. The postgresql container on my local server... What would be the host of this database? Is it the public IP of the ubuntu server? Not sure 2. Is there a better way to debug these network issues? I have been getting timeout errors (assuming this is because my django container is unable to reach my local db server) I have tried using the public IP of my local ubuntu server but that did not solve anything or tell me anything new. -
Djoser /jwt/verify/ is getting a 500 error even when I'm getting a local access token
In my react/redux django application, I am using JWT authorization. In my function to check whether the user is authorized, I am successfully consoling a Local Storage Token - however, the API Response is outputting a 500 error. In redux dev tools, Im only able to ever see AUTHENTICATED_FAIL, never success. I am getting a 500 error in postman as well when I post what is a correct Local Storage token. If it is relevant to this issue, whenever I refresh the page the user is forcibly logged out. Please help me / let me know what else is needed to best support. " `export const checkAuthenticated = () =\> async (dispatch) =\> { if (localStorage.getItem("access")) { console.log("Local Storage Token:", localStorage.getItem("access")); const config = { headers: { "Content-Type": "application/json", Accept: "application/json", }, }; const body = JSON.stringify({ token: localStorage.getItem("access") }); try { const res = await axios.post( `${process.env.REACT_APP_API_URL}/auth/jwt/verify/`, body, config ); console.log("API Response:", res); if (res.data.code !== "token_not_valid") { dispatch({ type: AUTHENTICATED_SUCCESS, }); } else { dispatch({ type: AUTHENTICATED_FAIL, }); } } catch (err) { dispatch({ type: AUTHENTICATED_FAIL, }); } } else { dispatch({ type: AUTHENTICATED_FAIL, }); } };` ```" Here is part of the error message from the server … -
How is Django typically used with Angular?
I started learning Django and it confuses me a little bit. Because I’m an Angular dev, I am confused about the Angular’s role. Angular is known for its flexible HTML, but it’s done by django, also I need to use state management, which I won’t be able to use if the data is already used by django and has generated HTML from it. Plus, page refreshes. Every url has its html, and switching urls will cause page refreshes, which we don’t want obviously. Also, frontend and backend are mixed in each other which is also confusing, seen as a Node/expressJs dev. I’m curious about how most of the people use them together, what is the ‘standart’ for building Django apps with frontend frameworks. -
Django not detecting Postgres version correctly
I had Postgres version 10.3. When I ran makemigrations, I got the error: django.db.utils.NotSupportedError: PostgreSQL 11 or later is required (found 10.23). So, I actualized Postgres, and created a new database. Now I have postgres 15.2 psql --version psql (PostgreSQL) 15.2 (Ubuntu 15.2-1.pgdg18.04+1) Still, Django thinks I have the old version of Postgres and gives me the same error. django.db.utils.NotSupportedError: PostgreSQL 11 or later is required (found 10.23). How can solve this? -
How to render html page via mail?
I tried to have main own password reset confirmation mail template and it doesn't work in sense cause is rendering in .txt and not .html I've tried with this view : class CustomPasswordResetView(PasswordResetView): @staticmethod def send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): subject = render_to_string(subject_template_name, context) subject = ''.join(subject.splitlines()) body_text = render_to_string(email_template_name, context) body_html = render_to_string(html_email_template_name, context) email_message = EmailMultiAlternatives(subject, body_text, from_email, [to_email]) email_message.attach_alternative(body_html, 'text/html') email_message.send() and also the urls.py path('password_reset/', auth_views.PasswordResetView.as_view( html_email_template_name='registration/password_reset_email.html' ), name='password_reset_confirm'), and i've created a password_reset_email.html file in the registration folder in templates But when i receive the mail is showing me the whole content in text, i can see the html tags... -
Django Rest Framework: How can I automatically set a value for Creation in generics API classes?
I want that my API that my api automatically assign the value user to the logged in user during the creation Process, but I can't figure how. Model: class Template(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='templates') name = models.CharField(max_length=200) base_attribute_points = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10000)]) base_skill_points = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10000)]) base_advantage_points = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10000)]) min_attribute_value = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(100)]) max_attribute_value = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(1000)]) replace_attributes_derived_values = models.BooleanField() replace_attributes_skills = models.BooleanField() def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return f'{self.user}: {self.name}' Serializer: class TemplateSerializer(serializers.ModelSerializer): characteristics = CharacteristicSerializer(many=True, read_only=False) attributes = AttributeSerializer(many=True, read_only=False) skill_categories = SkillCategorySerializer(many=True, read_only=False) derived_values = DerivedValueSerializer(many=True, read_only=False) levels = LevelSerializer(many=True, read_only=False) class Meta: model = Template fields = ['id', 'user', 'name', 'base_attribute_points', 'base_skill_points', 'base_advantage_points', 'min_attribute_value', 'max_attribute_value', 'replace_attributes_derived_values', 'replace_attributes_skills', 'characteristics', 'attributes', 'skill_categories', 'derived_values', 'levels'] View: class TemplateList(generics.ListCreateAPIView): serializer_class = TemplateSerializer queryset = Template.objects.all() permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user return user.templates.all() #def perform_create(self, serializer): # print(serializer.validated_data) # serializer.save() Like I said, I want to set the user to the logged-in user. Also It would be nice, if the user field isn't required. I already tried out many things, but all i get are errors. I tried to configure the perform_create method to change the value there, … -
Django admin panel makes unnecessary queries when memoizing related object in model __init__ method
Django = 2.2 Python = 3.6 I have two models named Pl and Exam in Django: class Pl(models.Model): name = models.CharField() class Exam(models.Model): name = models.CharField() pl = models.ForeignKey("Pl") def __init__(self, *args, **kwargs): super(Exam, self).__init__(*args, **kwargs) self._pl = self.pl As shown in the code, the Exam model's __init__ method makes a query to the Pl model to memoize it. This is causing problems on the admin panel, where if I want to display 100 Exam objects on the list page, it makes 100 queries for each object. I have tried using list_select_related = ("pl", ), but it didn't work. I have also tried to override the get_queryset method in the admin panel and use select_related("pl"), but it still makes those queries. To debug the issue, I updated the __init__ method as follows: def __init__(self, *args, **kwargs): super(Exam, self).__init__(*args, **kwargs) print(self._state.fields_cache) # name this print statement as "A" self._pl = self.pl And then I tried the following query: exams = Exam.objects.all().select_related("pl") exam = exams.last() print(exam._state.fields_cache) # name this print statement as "B" "B" always shows the cached field and returns {'pl': <Pl: 1>}, but "A" always returns an empty dictionary {} indicating that the self object doesn't have the cached object. … -
why is there an error while rendering django files
I did or tried, like here https://github.com/kottenator/django-compressor-toolkit and https://gist.github.com/brizandrew/685a588fbefbd64cd95ed9ec4db84848 But after the command "python manage.py compress" comes out this "CommandError: An error occurred during rendering accounts\profile.html: 'utf-8' codec can't decode byte 0xad in position 9: invalid start byte", at the same time, after each command, the name "profile.html" of the html file is different my settings.py COMPRESS_ENABLED = True COMPRESS_CSS_HASHING_METHOD = 'content' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) COMPRESS_FILTERS = { 'css': [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter', 'compressor.filters.template.TemplateFilter' ], 'js': [ 'compressor.filters.jsmin.JSMinFilter', ] } COMPRESS_PRECOMPILERS = ( ('module', 'compressor_toolkit.precompilers.ES6Compiler'), ('text/x-scss', 'compressor_toolkit.precompilers.SCSSCompiler'), ) HTML_MINIFY = True KEEP_COMMENTS_ON_MINIFYING = True COMPRESS_OFFLINE = True my template {% extends 'base-page.html' %} {# Django template #} {% load compress %} {% load static %} {% load pages %} {% compress css %} <link rel="stylesheet" type="text/x-scss" href="{% static 'accounts/css/base-profile.css' %}"> {% endcompress %} {% compress js %} <script type="module" src="{% static 'accounts/js/base-profile.js' %}"></script> {% endcompress %} my package.json { "name": "mysite", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "type": "module", "author": "", "license": "ISC", "devDependencies": { "autoprefixer": "^10.4.14", "babel-preset-es2015": "^6.24.1", "babelify": "^10.0.0", "browserify": "^17.0.0", "node-sass": "^8.0.0", "postcss-cli": "^10.1.0", "sass": "^1.59.3" }, "dependencies": { "jquery": "^3.6.4" } … -
Difference between ViewSet and GenericViewSet?
I have been a little confused lately with GenericViewSets and ViewSets. It started off by thinking what is the difference between APIView and GenericAPIView. A little search and I found out that APIView uses HTTP verbs(get, put post, etc) as their method names and they have to be explicitly implemented, whereas in GenericAPIView the method names are actions (list, create, destroy, update, etc) which are automatically mapped to the correct method call. But even these HAVE to be implemented. However, we can add mixins on top of GenericAPIView or use generics and then we do not have to implement the methods if they follow a basic CRUD pattern. Declaring just the queryset (get_queryset) and serializer_class(get_serializer) will suffice. My question is if the difference between ViewSets and GenericViewSets is same as APIView and GenericAPIView? Also, what if I want my class to inherit only the GenericViewSets( or GenericAPIView, for that matter), without using any mixins? How would GenericViewSets be any different from ViewSets then? PS. This is the image that got me thinking about everything. -
Using ForeignKey and ManyToManyField in Django model
I'm trying to set up this Django endpoint to create a new post. MODEL class UserPosts (models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='posts_created') text = models.CharField(max_length=300) likes = models.ManyToManyField(User, related_name='posts_liked') timestamp = models.DateTimeField(auto_now_add=True) SERIALIZER class UserPostsSerializer(serializers.ModelSerializer): class Meta: model = UserPosts fields = ['id', 'user', 'text', 'likes', 'timestamp', 'user_id'] depth = 1 user_id = serializers.IntegerField(write_only=True) likes = UserSerializer(read_only=True, many=True) #NOT SURE IF RELEVANT, BUT THE USERSERIALIZER LOOKS LIKE THIS class UserSerializer(serializers.ModelSerializer): class Meta: model = User VIEWS @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def get_all_posts(request): if request.method == 'GET': posts = get_list_or_404(UserPosts) serializer = UserPostsSerializer(posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = UserPostsSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user=request.user, user_id=request.user.id) return Response(serializer.data, status=status.HTTP_201_CREATED) If I test the endpoint in Postman, I get a 400 error Bad Request saying "user_id": "this field is required". I've set up ForeignKey fields exactly like this in the past and it worked. But I haven't used a ManyToMany field in this way before. I'm thinking the issue is in my serializer? -
How to return a QuerySet of 2 models via reverse ForeignKey lookup in Django?
I have "Parameter" and "ParameterChoice" models where I define multiple choices for each parameter. The end goal is to have some sort of assessment where I have a list of parameters where each parameter has a specific fixed set of choices available for selection from a dropdown list within the HTML template. I want to somehow pass one or two querysets to the template where I will render a table of all parameters and available choices next to it. Unfortunately, I really struggle to come up with logic in Django on how to achieve this. Ideally, result would look like this: Parameters Choices Param1 ChoiceA ChoiceB ChoiceC Param2 ChoiceY ChoiceZ How can I make this happen without a raw SQL query? Current setup: models.py class Parameter(models.Model): text = models.CharField(blank=False, null=False, max_length=200) class ParameterChoices(models.Model): text = models.CharField(blank=False, null=False, max_length=200) parameter = models.ForeignKey(Parameter, related_name='parameterchoices', on_delete=models.CASCADE, blank=False, null=False) views.py def parameters(request): params = Parameter.objects.all() param_choices = ParameterChoices.objects.all() context = { 'parameters': params, 'parameter_choices': param_choices, } return render(request, 'questionnaire/parameters.html', context) -
Issue: NOT NULL constraint failed
So I'm currently building an online webshop for my school project. In the webshop, the user should be able to submit a review on each product. Tho I'm having issues when trying to submit the review. It gives me this error: NOT NULL constraint failed: Ive been stuck on this for about 15 hours I cant seem to solve it. I would appreciate all the help I can get. Traceback: Traceback (most recent call last): File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: products_reviewrating.user_id) was the direct cause of the following exception: File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/workspace/webster00/products/views.py", line 91, in submit_review newreview.save() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1410, in execute_sql cursor.execute(sql, … -
How to write out an object from a relationship in django
I don't know how to describe this exactly in database jargon. I would like to output an object that is in a relationship with another like this. order__orderitem.product.title models.py class Order(models.Model): status_types = [ ("Ordered", "Ordered"), ("Sent", "Sent"), ("Delivered", "Delivered"), ("Extended", "Extended"), ("Returned", "Returned"), ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order_date = models.DateTimeField() return_date = models.DateTimeField(null=True) status = models.CharField(choices=status_types, default="Ordered", max_length=100) total = models.IntegerField(null=False) payment = models.OneToOneField(Payment, on_delete=models.CASCADE, null=False, blank=False) shipping = models.ForeignKey(Shipping, on_delete=models.CASCADE, null=False, blank=False) first_name = models.CharField(max_length=255, null=False, blank=False) last_name = models.CharField(max_length=255, null=False, blank=False) phone = models.CharField(max_length=12, null=False, blank=False) city = models.CharField(max_length=255, null=False, blank=False, default=None) zip_code = models.CharField(max_length=10, null=False, blank=False, default=None) street = models.CharField(max_length=255, null=False, blank=False, default=None) building_number = models.CharField(max_length=10, null=False, blank=False, default=None) apartment_number = models.CharField(max_length=10, null=True, blank=True, default=None) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) price = models.IntegerField(null=False, blank=False, default=15) debt = models.IntegerField(null=True, default=0) orders.html {% for item in object_list %} {% for it in item__OrderItem %} {{ it.product.title }} {% endfor %} {% endfor %} Is it possible in such a way? -
How to fix Page not found in Django?
I have created a template for menu showing, but when I run my server, I got an error that my page is not found. Any suggestions? from django.urls import path from restaurant import views app_name = 'restaurant' urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name = 'about'), path('menu/<slug:menu_name_slug>/', views.show_menu, name='show_menu'), path('restricted/', views.restricted, name='restricted'), ] Error Message: Using the URLconf defined in WAD_Group_Project.urls, Django tried these URL patterns, in this order: [name='index'] restaurant/ [name='index'] restaurant/ about/ [name='about'] restaurant/ restaurant/menu/<slug:menu_name_slug>/ [name='show_menu'] restaurant/ restricted/ [name='restricted'] admin/ accounts/ ^media/(?P<path>.*)$ The current path, restaurant/menu/, didn't match any of these. -
How to use vuejs with django
I'm trying to use vue (with a cdn) in an html file located in home(the django app)/templates/index.html. I included the cdn in the body, here is the code: <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <div id="app">{{ message }}</div> <script> const { createApp } = View createApp({ data() { return { message: 'Hello Vue!' } } }).mount('#app') </script> Nothing is displayed on the page and I have this error in the console: [Vue warn]: Component is missing template or render function. at <App> What's wrong with this code? -
Django-NextJS not rendering webpages properly
I have a Django server which I am trying to integrate NextJS into using the django-nextjs python package. Everything works fine except that when I open the Django server on port 8192, it renders the path to the webpage instead of the actual webpage itself i.e. http://localhot:8192/home renders '/home' in the browser. No HTML tags, no JS, just the string /home. The NextJS server however does not do this: it renders the whole page as expected so I think that this is something to do with django-nextjs and not the NextJS server itself. The strangest thing is that it was working just fine before. I have tried printing the output from django-nextjs and have confirmed that it is either django-nextjs or the NextJS server that is causing the issue. However as previously stated the Next server returns the pages, while Django does not. Any pointers are appreciated :) Files mainserver/asgi.py import os from channels.routing import ( ProtocolTypeRouter, URLRouter, ) from django.core.asgi import get_asgi_application from django_nextjs.proxy import ( NextJSProxyHttpConsumer as NextHttpConsumer, NextJSProxyWebsocketConsumer as NextWebsocketConsumer, ) from django.urls import path, re_path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainserver.settings') http_urls = [ re_path(r'', get_asgi_application()), #re_path(r"^(?:_next|__next|next).*", NextHttpConsumer.as_asgi()), ] websocket_urls = [ path("_next/webpack-hmr", NextWebsocketConsumer.as_asgi()) ] application = ProtocolTypeRouter({ 'http': URLRouter(http_urls), … -
Django view and serializer of manyToMany using through
I have the following structure: Each account has list of stores, and each store has list of lines. models: class Account(models.Model): name = models.CharField(max_length=50, unique=True) lines = models.ManyToManyField('Line', through='AccountLine', related_name='accounts') class Store(models.Model): type = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255) class ExtendedData(models.Model): x1 = models.BooleanField(default=False) x2 = models.IntegerField(default=0) class Line(models.Model): name = models.CharField(max_length=255) store = models.ForeignKey('Store', on_delete=models.DO_NOTHING) class Meta: unique_together = ('store', 'name') class AccountLine(models.Model): account = models.ForeignKey('Account', on_delete=models.DO_NOTHING) line = models.ForeignKey('Line', on_delete=models.DO_NOTHING) extended_data = models.ForeignKey('ExtendedData', on_delete=models.DO_NOTHING) is_active = models.BooleanField(default=False) class Meta: unique_together = ('line', 'account') I need to create a list view of account's stores, and for each stores the list of connected lines, including the 'through' extra fields 'is_active' , like the following json: [ { "id": 0, -- Store id "type": "store_type_1", "name": "Store1", "lines": [ { "id": 0, -- Line id "name": "Line1", "extended_data": { "x1": true, "x2": 0 }, "is_active": true } ] } ] -
Django quiz form
I have page with some article and some kind of quiz below. I have questions and choices(options in my program) in db. I need to make quiz form where labels are questions from db and choices are options from db. I was looking for some solution and found. But it doesn't work, on page I have nothing, just submit button without form fields forms.py from django import forms from .models import QuestionOption class TestForm(forms.Form): def __init__(self, allQuestions, *args, **kwargs): self.questions = allQuestions for question in allQuestions: field_name = question.question choices = [] for choice in QuestionOption.objects.filter(question=question.id): choices.append((choice.id, choice.option)) field = forms.ChoiceField( label=question.question, required=True, choices=choices, widget=forms.RadioSelect) return super(TestForm, self).__init__(*args, **kwargs) models.py from django.db import models class Topic(models.Model): topic = models.TextField() def __str__(self): return self.topic class Question(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) question = models.TextField() def __str__(self): return self.question class QuestionOption(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) option = models.TextField() is_correct = models.BooleanField() def __str__(self): return self.option class TopicMaterials(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() presentation = models.TextField() def __str__(self): return self.topic views.py from django.contrib.auth.decorators import login_required from .forms import TestForm from django.http import HttpResponseNotFound from django.shortcuts import render from .models import Topic, Question, QuestionOption, TopicMaterials @login_required def article(request): topicNum = request.GET.get('topic') if Topic.objects.filter(id=topicNum).exists(): …