Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django IntegrityError (null value in column violates not-null constraint) allows model object to be saved but then deletes object?
When troubleshooting the error django.db.utils.IntegrityError: null value in column "experience" violates not-null constraint DETAIL: Failing row contains (7, f, null, 1, 1, null, 5)., I added a save function to my model to print out the experience value so that I could see if it was really null or not. The experience value being saved is not null. When I ran my code after adding this save function, the object seemed to be created successfully without error when I click 'save' in helm. But, when I go to view my Scheduler objects, nothing appears there. Additionally, I get the message at the top of helm that my object was created successfully along with a message that the schedule event with ID "None" does not exist. I am really confused on why this is happening. My guess is that the save method I added is making it so that Django is not checking to see if errors exist which causes the object to appear created when it is not. I am fairly certain that the IntegrityError still exists and that this is related to why the object is deleted immediately after creation. I would appreciate any help someone can provide. Django … -
django media images wont display
I have deployed a Django project on a server. The project has a blog app in which you can add posts from the admin page. Each post has some paragraphs, a title, and an image. The posts get created perfectly, but sometimes when I revisit the site, the pictures I uploaded don't display. I have found out that if I clear the browser's cache by pressing ctrl+f5, the images will get displayed. But this is not ok, and I cant tell every user to clear their browser cache, obviously. here is a sample of this problem: and everything goes back to normal after cache clearing. this is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and I have added this line in my main urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to style form's dropdown options and add picture, instead of a generic list using Django
I want to have a user's profile pic and the value in the database when trying to submit a form. Currently the form just has a drop down that lists all the objects' ids in the DB, example: Object (1) Object (2) Object (3) Object (4) Object (5) I want the drop down to have: Username, profile pic (their actual image from static files), Object 1's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 2's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 3's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 4's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 5's string (whats actually in the DB) Here is some code, i'm open to any python solution (crispy/widget/etc.) My form.py from django.contrib.auth import get_user_model from .models import Observation, Data, Hypothesis, Experiment, Comment User = get_user_model() class SubmitObservation(ModelForm): description = forms.CharField(widget=forms.Textarea, label='Submit an Observation') class Meta: model = Observation fields = ('description',) exclude = ('user', 'status', 'activate_date', 'deactivate_date') #observation = forms.CharField(label='Observation', max_length=250) class SubmitData(ModelForm): data_description = forms.CharField(widget=forms.Textarea, label='Data') … -
csrf token missing axios to django rest framework
i was trying to make post request and face with error code 403,csrf token was missing.. tried many methods but didnt work at last disabled csrf token on settings.py and worked , so found the problem was in csrf token class Axios extends React.Component{ constructor(){ super() this.state = { persons: [] } } post(){ axios.post('http://127.0.0.1:8000/api/create', { title: 'titan', body: 'this is working', }) .then(function (response) { console.log(response); }) } get(){ axios.get('http://127.0.0.1:8000/api').then(Response=>{ console.log(Response.data) }) } componentDidMount(){ this.post(); this.get(); } render(){ return( <div> <h1>fetch</h1> </div> ) } } export default Axios; this is my code pls tell me a way to put csrf token in this as well as import statement... currently using axios -
Get User Specific Answer attribute from primary model instance - django
I have a Question model and then an Answer Model. Answer model saves answers specific to the logged-in user. I have successfully saved the answer of the login user and verified it in the admin. However, I am unable to get the answer, specifically for the logged-in user. Can you please point me in the right direction? I have already tried https://docs.djangoproject.com/en/3.1/ref/models/relations/ My Model: class Question(models.Model): question = models.CharField(max_length=200, null=True, blank=True) edit_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) answer = models.TextField(max_length=600, null=True, blank=True, default=" ") edit_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.answer My View def InterviewQuestion(request): questions = Question.objects.all() context = {'questions':questions} return render(request, 'jobs/ace-interview.html', context) My Template {% for question in questions %} <div class="card"> <div class="card-body"> <h5 class="card-title">{{question.question}}</h5> <p class="card-text">{{question.answer_set.answer}}</p> </div> </div> {% endfor %} I want Answer here specific to the user -
Django Admin Panel can't access specific items
I've got a model of an article and everything works fine except when I change their status to draft - it disappears from Admin Django Panel. New articles are successfully added, but then don't show, admin panel just can't access them. When I change the URL to force the admin panel to show me the details so I could edit it, I get a message that the article with given ID doesn't exist. So basically every draft article gets lost. But I know they have to exist in my database, because they show up on my article list view, but I can't go to detail view or draft view as I always get "No NewsModel matches the given query" Django 2.0.5 models.py class NewsModel(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) title = models.CharField(max_length=250) slug = AutoSlugField(populate_from='title') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES) image = models.ImageField(upload_to="news/") description = models.TextField(null=True, blank=True) def get_absolute_url(self): from django.urls import reverse return reverse('main:news_details', kwargs={'slug':self.slug}) def __str__(self): return self.title class Meta: ordering = ('-publish',) verbose_name = 'News' verbose_name_plural = 'News' admin.py @admin.register(NewsModel) class NewsAdmin(admin.ModelAdmin): list_display = ('title', 'game', 'news_type', 'author', 'finish', 'publish') views.py def news_details(request, slug): … -
Problems with django-microsoft-auth
A customer told me that he needs to make a system, in Django, that authenticates users against Azure Active Directory. I'm trying to use django-microsoft-auth (https://django-microsoft-auth.readthedocs.io/en/latest/usage.html) but I have several problems. When I'm going to execute the test site, I have the following error: ModuleNotFoundError: No module named 'tests.site' so I don't see how this test site works. I'm executing in Windows 10, 64 bits. I already do the conection to Azure Active Directoy but I don't know can I see the user that it's connected, make a login and a logout link, manage the user permits. I think that the quick start guide it's very poor for Django beginners deverlopers, like me, because not especify all of this items. I will ver glad if somebody can help me. I have spent many hours trying to solve these problems. Thanks. -
Django migration throws relation does not exist before migration makes the table
I'm trying to start from a clean database and run all the migrations, but I have a for that's used in a view that has options that it pulls from the database. When I try to run the migration, it throws an error. Commenting out the code fixes it, but this doesn't seem like a good solution for deploying to new environments. I've seen other questions where the answer is to just comment out your urls.py, but I was wondering if anyone found a clean solution for this? -
I am not able to add item to database
I have a product model, which i have the modelforms to make a form for and then implemented in my views and templates. After submitting the form, the product is not being added to the database and I don't know what the error seems to be. I made sure to use the enctype="multipart/form-data" because of the image field in the form and also request.FILES. N.B:I am getting Error Adding Product which is the else statement if the form is not valid, but i don't know how the form is not valid. models.py class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() image = models.ImageField(upload_to='images/products', default='images/products/default-product.jpeg', blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) is_favourite = models.ManyToManyField(User, related_name='favourite', blank=True) country = CountryField(blank_label='(select country)') def __str__(self): return self.name forms.py class AddProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' exclude = ['user'] views.py @login_required @supplier_required def Addproduct(request): title = "Add New Product" form = AddProductForm() if request.method == 'POST': form = AddProductForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, "Product Added Successfully") return redirect('product') else: messages.error(request, "Error Adding Product") context = {"form":form, "title":title} return render(request, "core/addproduct.html", context) addproduct.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} … -
MultipleChoiceFilter to Checkboxes
I have a ModelMultipleChoiceFilter working, however I cant find a way to adjust it from a input multiple choice to a checkbox list. This is what I currently have: This is what I want to convert it to: My current code: class GameFilter(django_filters.FilterSet): gamemodes = django_filters.ModelMultipleChoiceFilter( queryset=GameMode.objects.all(), label='Game modes (or)', ) -
how to create urls/path in django restframework?
My project structure is like this: project |----app1 |--app1.1 |--app1.2 |--app1.3 so my question is how to add url/path? -
Django Many to Many Fields Not Saving Rest Framwork
Hi guys I'm trying to save many to many data from rest Post method when I post it give me blank none items added to many to many fields. Please check and help me how I can fix this issue Views.py @api_view(['POST', 'GET']) def AddDisco(request, *args, **kwargs): if request.method == 'POST': data=request.data serializer = serializers.DiscoSerializer(data=data) if serializer.is_valid(): print('it is valid') serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) if request.method == 'GET': qs = Disco.objects.all() serailzer = serializers.DiscoSerializer(qs, many=True) return Response(serailzer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_200_OK) Models.py class MusicGenre(models.Model): title = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=100) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Disco(models.Model): title = models.CharField(max_length=100) genre = models.ManyToManyField(MusicGenre, blank=True) Serializer.py class DiscoSerializer(serializers.ModelSerializer): class Meta: model = models.Disco fields = '__all__' depth = 1 when I try to post from api it wont add the items in genre it gives me blank Please help me to solve this issue -
How to get data correctly from a django model to Django REST framework
I'm working with Python 3.9 and Django 3.1.6. I have a quite long model in models.py. Short version is something like this: class Check (models.Model): @property def total_body_fat_percentage(self): if self.client_gender == "M": total_body_fat_percentage = (self.Yuhasz * 0.097) + 3.64 pass else: total_body_fat_percentage = total_body_fat_percentage = float((self.Yuhasz * 0.1429) + 4.56) return total_body_fat_percentage @property def muscle_weight_percentage(self): muscle_weight_percentage =self.muscle_weight*100/self.weight return muscle_weight_percentage These fields return a float number. Something like 14.407. Of course there are other fields in there such as Yuhasz, client_gender, etc. I need these values into JSON. I tried to use the following serializer on serializer.py: class PercentagesSerializer(ModelSerializer): class Meta: model = Check fields = ('total_body_fat_percentage', 'muscle_weight_percentage') And I have the following class on views.py: class PercentagesAPI(APIView): authentication_classes = [] permission_classes = [] serializer = PercentagesSerializer def get(self, request, format=None): lista = Check.objects.all() print(lista) response = self.serializer(lista) print(response) json_response= json.dumps(response.data) print(json_response) data = { 'percentages': json_response } return Response(response.data) But it returns no data. Shell console states that it gets the queryset, it gets the fields, but it doesn't seems to get the values: <QuerySet [<Check: Check object (1)>]> PercentagesSerializer(<QuerySet [<Check: Check object (1)>]>): total_body_fat_percentage = ReadOnlyField() muscle_weight_percentage = ReadOnlyField() {} Thank you in advance for your advices and help! -
Facing HTTPError 404
I am using Django as frontend and Firebase as backend. I am trying to render a html page after a post request. As I tried to run the program I am getting HTTPError 404 Here is my view.pyViews.p After I run the http://127.0.0.1:8000/post_create/ on Chrome I get the following error Error I am trying to solve this problem from 3-4 days but unable to get solution. I am not getting why this error is occuring. Your help would be appreciated Thank you. -
Display Multiple Chart.js Charts in Django Template Using Loop
I want to filter multiple charts using for loop in django template. The data displays correctly, and I can get it to display the first chart only. Guys, i am having trouble using for loop in django template i do not know how to use for loop to display multiple charts in django template i am unable to find solution of displaying multiple charts and django kindly help me please. Template {% for data in data_list %} <div class="box col-lg-3 pull-up"> <div class="box-footer p-0 no-border"> <div class="chart"> <canvas id="chartjs" class="h-80"></canvas> </div> </div> </div> {% endfor %} <script> $(function () { 'use strict'; //----chart var dasChartjs = document.getElementById("chartjs").getContext("2d"); var blue_trans_gradient = dasChartjs.createLinearGradient(0, 0, 0, 100); blue_trans_gradient.addColorStop(0, 'rgba(247, 147, 26,1)'); blue_trans_gradient.addColorStop(1, 'rgba(255,255,255,0)'); var DASStats = { responsive: true, maintainAspectRatio: false, datasetStrokeWidth : 3, pointDotStrokeWidth : 4, tooltipFillColor: "rgba(247, 147, 26,0.8)", legend: { display: false, }, hover: { mode: 'label' }, scales: { xAxes: [{ display: false, }], yAxes: [{ display: false, ticks: { min: 0, max: 85 }, }] }, title: { display: false, fontColor: "#FFF", fullWidth: false, fontSize: 30, text: '52%' } }; // Chart Data var DASMonthData = { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"], datasets: [{ label: … -
ValueError: Field 'id' expected a number but got 'example@example.com'
I'm trying to create a superuser but it's giving the above error. And I can't exactly find at which line I'm getting the error. views.py from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from .models import * from django.http import HttpResponseRedirect from django.urls import reverse from .form import * from django.db import IntegrityError # Create your views here. def index(request): if not myUser.is_authenticated: message = "signed in as {Customer.first_name}" else : message = "please sign in" return render(request, "auctions/index.html",{ "listings": Listings.objects.all(), "message":message }) def login_view(request): if request.method == "POST": form = loginForm() email = request.POST["email"] password = request.POST["password"] user = authenticate(request,username=email,password=password) if user is not None: login(request,email,password) return HttpResponseRedirect(reverse('index')) else: return render(request, "auctions/login.html",{ "form": form , "message": "username/password not valid" }) return render(request, "auctions/login.html",{ "form": loginForm() }) def logout_view(request): logout(request) return render(request, "auctions/login.html") def register(request): if request.POST == "POST": form = registerForm() email = request.POST["email"] # check passwords are same password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render (request, "auctions/register.html",{ "form": form, "message": "Passwords does not match" }) # Attempt to create new user try: user = myUser.objects.create_user(email,password) user.save() except IntegrityError: return render(request, "auctions/register.html", { "form":form, "message": "Username is already taken" }) login(request,user) return HttpResponseRedirect(reverse('index')) return … -
Django deployment on web host
For past three days/nights i have been trying to deploy a django app on bluehost hosting, the trouble is bluehost do not provide builtin python application installer like others rather we have to register application once deployed, i would really appreciate if anyone could point me to right direction. So far I have installed python 3.6 and pip Installed django uploaded django project files to server i run python manage.py runserver It runs on local host fine I have multiple domains on my hosting plan but I don’t understand how to deploy django to one of my domains.. PS I am absolute beginner to django framework so any help Is appreciated Thanks -
Docker-compose is not reading env variable COMPOSE_FILE
I am using django cookiecutter configuration with Docker and I can not make docker-compose read $COMPOSE_FILE env variable. I did this export COMPOSE_FILE=local.yml And this is the outcome when a I run either docker-compose up or build: Can't find a suitable configuration file in this directory or any parent. Are you in the right directory? Supported filenames: docker-compose.yml, docker-compose.yaml -
Welcome to CentOS - Django, Nginx & uwsgi
Installed and configured nginx/uwsgi for django application. Both services are running fine no errors. But facing Welcome to CentOS when loading application in browser. nginx.conf --- content server { listen 80; server_name ##.com www.###.com; # location = favicon.ico { access_log off; log_not_found off; } location /media/ { alias /home/crmuser/crmsourcedirect/media/; } location /static/ { alias /home/crmuser/crmsourcedirect/static/; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass unix:/run/uwsgi/crmsourcedirect.sock; # uwsgi_pass 127.0.0.1:8000; } } crmsourcedirect.ini -- content [uwsgi] project = crmsourcedirect username = crmuser base = /home/%(username) logto = /var/log/uwsgi/uwsgi.log chdir = %(base)/%(project) home = %(base)/venv module = cmo.wsgi:application master = true processes = 5 uid = %(username) socket = /run/uwsgi/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true ''' -
django rest nested serializer object setting nested object in post method
hi guys i hope you be healthy :) okay i have an image model and a category model which have a foreignkey to image model like below: image model: class Image(models.Model): image = models.ImageField(upload_to="%Y/%m/%d") alt = models.CharField(max_length=25) name = models.CharField(max_length=25, unique=True) def __str__(self): return self.name category model: class Category(models.Model): image = models.ForeignKey(Image, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=25, unique=True) slug = models.SlugField(max_length=25, unique=True) okay now i want to when i call a category get somting like this: { "image":{ "image":"https://example.com/media/image.png", "name":"image name", "alt":"image alternative" }, "name":"category name", "slug":"category slug" } i write my serializer and views like below and getting a god json object like above image serializer: class ImageSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) image = serializers.ImageField() alt = serializers.CharField(max_length=25) name = serializers.CharField(max_length=25, validators=[UniqueValidator(queryset=Image.objects.all(), message="there is another image with same name.")]) category serializer: class CategorySerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) image = ImageSerializer() name = serializers.CharField(max_length=25,validators=[UniqueValidator(queryset=Category.objects.all()),]) slug = serializers.SlugField(max_length=25,validators=[UniqueValidator(queryset=Category.objects.all(),]) def validate_image(self, value): return get_object_or_404(Image, name=value['name']) def create(self, validated_data): return Category.objects.create(**validated_data) def update(self, instance, validated_data): instance.image = validated_data.get('image', instance.image) instance.name = validated_data.get("name", instance.name) instance.slug = validated_data.get("slug", instane.slug) instance.save() return instance and here is category view: class CategoriesView(APIView, PaginationMixin): pagination_class = PageNumberPagination() permission_classes = (AllowAny,) def get(self, request): cats = Category.objects.all() serializer = CategorySerializer(cats, many=True, context={"request":request}) … -
start gunicorn when docker-compose is not in same folder
I am attempting to build an environment, using Docker, Django, gunicorn, postgres and nginx. In this environment Dockerfile and docker-compose sits one level above src folder My idea of folder structure is as follows: "NN Project" folder within my "Documents/repositories" └── / config (to place nginx settings within) └── / deployment (to place environment "secrets" within) └── / src (the Django project) ├── Dockerfile ├── docker-compose ├── license, readme ... ├── build_script.sh The reason I want to put Dockerfile and docker-compose at top-level and not under the sub-folder /src is because I want the ability to access env "secrets" when working in a container with Django and its relative import NON_VERSION_PATH = Path(__file__).resolve().parent.parent.parent with open(NON_VERSION_PATH / 'deployment/etc/application/.env_vars', 'r') as f: secrets = json.loads(f.read()) Problem I have is that I cannot get web (the "src" container) to start (it cannot find it). However, it works fine if I place Dockerfile and docker-compose within the /src folder but I would like to have the docker-compose one level up. I understand it is about relative import, however, I cannot figure out how to tell it to look in ./code my docker-compose looks like: version: "3.9" services: db: container_name: db image: postgres:alpine restart: always … -
How we can secure our videos in Django for Lms that no one can download
I am creating an LMS and wanted to secure my video content but don't want to use any third party to host my video like Vimeo etc. How can we do this is in Django. Is this even possible? -
How to catch a Django "GET" event in template using jquery?
In my Django project, I have a pdf download button that generates a report. When I push the button I would like a modal showing that the report is being processed. When the pdf is downloaded, I would like the modal to hide automatically. However, I am having some trouble with the last part. I know that Django sends a "GET" message in the backend, when the report is downloaded ("GET /download/140/...") How can I "catch" the ("GET /download/140/...") event in my template? Code: <a href="{% url 'report-download' object.id %}" class="btn btn-grey" id="pdf-button"></a> Show "processing" modal when download is initiated... <script type="text/javascript"> $("#pdf-button").on("click", function(){ $('#myPDFModal').modal('show'); }); </script> Attempt: Close "processing" modal when download is finished using Ajax... <script type="text/javascript"> $(document).on('click', '#pdf-button', function(event) { event.preventDefault(); $.ajax({ url: '{% url 'report-download' object.id %}', type: 'GET', }).done(function(result) { $('#myPDFModal').modal('hide'); }); }); </script> The above code seems to work at showing/hiding the modal at the right "GET" event, but the pdf is not downloaded.. -
How to call celery task with class based method?
I have the class: class Parser: def __init__(self): self.OM = Omni() # Creates an class object, which makes auth on the web site, for scrapping @app.task def foo(self, data): self.OM.parse(data) So how can I call task with foo method? Because when I try to do like this, I takes error : Missing argument data. I think it is because calling the method get data as self parameter prs = Parser() prs.foo.delay(data) How I can to resolve it? -
how to fix django.db.utils.ProgrammingError:relation "some_object" does not exist?
How to fix django.db.utils.ProgrammingError: relation "some_object" does not exist? I saw lots of topic on this platform to related this error, but won't able to fix it in my case. In my case means, I am working on django and I have the postgresql database and It's working well but whenever I took pull request from git(where other person is working) and run the migration then I am getting this error. below is some links that I had tried https://stackoverflow.com/a/33055243/11360069 I just try but not working https://stackoverflow.com/a/46697898/11360069 ./manage.py migrate --fake default https://stackoverflow.com/a/29672770/11360069 python manage.py migrate --run-syncdb and python manage.py migrate --fake appname python manage.py migrate --fake, python manage.py migrate --fake--initial, python manage.py migrate Only one way is working for me when I had create a new database and applying migration. But I am not sure that what will happen if, if I'll update this code on server then it will show same error then we can't delete or change the exiting database.