Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django OneToOneField is causing IntegrityError at /submissions/submit/ NOT NULL constraint failed: submissions_submissiondata.submission_code_id
I'm trying to implement a model in such a way that a User can have multiple submissions, and a Submission has only one object of type SubmissionData. On the template, user will upload a PDF file, this PDF will be parsed, some info associated with that submission will be stored in the SubmissionData, and the file and some main information will be associated with the SubmissionData here is the models.py: class Submission(models.Model): submission_user = models.ForeignKey('auth.User', related_name='submissions', on_delete=models.CASCADE) submission_file = models.FileField(upload_to='media/') created_at = models.DateTimeField(auto_now=True) def __str__(self): user_submission = str(self.submission_user.username).lower() user_submission = user_submission + '/' + str(timezone.now()) return user_submission class Meta: ordering = ['-created_at'] class SubmissionData(models.Model): submission_code = models.OneToOneField(Submission, related_name='data', on_delete=models.CASCADE) uuid = models.CharField(max_length=250, null=True) patiente_name = models.CharField(max_length=250, null=True) patiente_age = models.PositiveIntegerField(null=True) patient_gender = models.CharField(max_length=20, null=True) and on my views.py: class SubmissionCreateView(CreateView, LoginRequiredMixin): form_class = SubmissionForm template_name = 'submissions/submission_create.html' success_url = reverse_lazy('submissions:list') def proccess_submission_data(self): parser = PDFParser('path-to-pdf').parse() data_obj = parser.get_result() submission_data = self.enconde(data_obj) self.object.save() submission_data.save() def enconde(self, data_obj): submission_data = SubmissionData(submission_code=self.object, uuid=data_obj.uuid, patiente_name=data_obj.patiente_name, patiente_age=data_obj.patiente_age, patient_gender=data_obj.patient_gender) return submission_data def form_valid(self, form): self.object = form.save(commit=False) self.object.submission_user = self.request.user self.proccess_submission_data() return super().form_valid(form) For some reason I'm getting the following error: And the error is triggered on those lines: Does anyone know what could be causing … -
how to show variations Sizes of Products in Django Admin
I have finally added variations to my order items so now I add items with different sizes S,M and L When I add the variations to the admin to be displayed it comes back with ERRORS: <class 'core.admin.OrderItemAdmin'>: (admin.E109) The value of 'list_display[3]' must not be a ManyToManyField. So how show i show the Size variation in the admin: here is the models: class VariationManager(models.Manager): def all(self): return super(VariationManager, self).filter(active=True) def sizes(self): return self.all().filter(category='size') def colors(self): return self.all().filter(category='color') VAR_CATEGORIES = ( ('size', 'size',), ('color', 'color',), ('package', 'package'), ) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField( max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True) price = models.FloatField(null=True, blank=True) objects = VariationManager() updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) def __str__(self): return f"{self.quantity} of {self.item.title}" and here is the admin.py class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'billing_address', 'out_for_delivery', 'received', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'user', 'shipping_address', 'billing_address', 'payment', 'coupon' ] -
<bound method class.method of <Class: >>
This is my models.py: Class User(AbstractBaseUser): first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return "%s %s" % (self.first_name, self.surname) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user}'s profile" def full_name(self): return f"{self.first_name} {self.surname}" class Composition(models.Model): title = models.CharField(max_length=120) composer = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return f"{self.title} {self.composer.full_name}" I can't understand why I'm getting Title <bound method Profile.full_name of <Profile: MyName's profile>> in the Django admin site, in the list of compositions' titles. Calling self.composer.full_name() only gets me two <bound method...> items. Can someone please help me? I've been battling with this for a while now and I'm stuck. -
Unable to set custom Django user model to is_active
I recently created a custom user model in a Django 1.11 project. It's tied into Django Registration and overall is working well. However, I get an error when trying to set a user as 'active' in the admin panel. The error I get is: normalize() argument 2 must be str, not None With the error generated due to this function: class UsernameField(forms.CharField): def to_python(self, value): return unicodedata.normalize('NFKC', super(UsernameField, self).to_python(value)) Here is my customer user model: from django.conf import settings from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField('email address', unique=True) first_name = models.CharField('first name', max_length=30, blank=True, null=True) last_name = models.CharField('last name', max_length=150, blank=True, null=True) username = models.CharField('username', max_length=150, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = 'user' verbose_name_plural = 'users' Here is the form I use when saving new users: from django import forms from django_registration.forms import RegistrationForm from users.models import User class CustomRegistrationForm(RegistrationForm): # remove password confirmation def __init__(self, *args, **kwargs): super(CustomRegistrationForm, self).__init__(*args, **kwargs) self.fields.pop('password2') first_name = … -
How to write image source in javascript with image name obtained from Django AJAX call
I have an image name "not the complete file path" obtained from Django AJAX call. The object has so many values. I return json object. Then, I purse it to process it in javascript. I have some errors in the following: $(document).on('click', '#post-det', function(e) { e.preventDefault(); var post_id = $(this).children(':first-child').text(); var post_id = parseInt(post_id); $.ajax({ type: "GET", url: "{% url 'get_post_details' %}", dataType: "json", data: { "post_id": post_id }, success: function(data) { alert(data); post_details(data); } }); }); function post_details(details) { var json = JSON.parse(details); var userusername= $('#user-username').text(json.user_username); alert(json.title); var post_images = $('#post-imgs').html(''); // RESET THE images div alert(json.images[0].image); for( var i = 0; i < json.images.length; i++) { post_images.html('<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">'+ '<ol class="carousel-indicators">'+ '<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>'+ '<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>'+ '<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>'+ '</ol>'+ '<div class="carousel-inner">'+ '<div class="carousel-item active">'+ '<img src='".."+"/"+".."+"/"+".."+"/"+".."+"/"+"media"+"/"+json.images[0].image+' class="d-block w-100" alt="...">'+ '</div>'+ '</div>'+ '<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">'+ '<span class="carousel-control-prev-icon" aria-hidden="true"></span>'+ '<span class="sr-only">Previous</span>'+ '</a>'+ '<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">'+ '<span class="carousel-control-next-icon" aria-hidden="true"></span>'+ '<span class="sr-only">Next</span>'+ '</a>'+ '</div>'); } } I have error in the following line '<img src='".."+"/"+".."+"/"+".."+"/"+".."+"/"+"media"+"/"+json.images[0].image+' class="d-block w-100" alt="...">'+ Any help or suggestion will be highly appreciated. I prefer the solution to be in the javascript side NOT in Django. I could alert the … -
Django CSRF protection, gives 200 ok response even though I didn't provide csrf token
didn't provide {% csrf_token %} in template, yet the http response is 200 ok, shouldn't be 403 forbidden ?! setting.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] url.py urlpatterns = [ path('admin/', admin.site.urls), path("formtest", view.formPostTest), ] template formPostTest.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <form class="" action="/formtest" method="post"> <label for="username">username: </label><input type="text" name="username" value=""> <label for="password">password: </label><input type="password" name="password" value=""> <input type="submit" name="submit" value="submit"> </form> </body> </html> view.py def formPostTest(request): if request.method == "GET": cont = {} return render(request, "formPostTest.html", cont) elif request.method == "POST": return HttpResponse("done") not only that I tired to do every thing to miss it up, I tampered with the csrftoken cookie network monitor screen shot it alaways give 200 ok resopnse no matter what the only problem it give in console console Forbidden (CSRF cookie not set.): /formtest Forbidden (CSRF cookie not set.): /formtest [07/May/2020 02:21:07] "POST /formtest HTTP/1.1" 200 4 and some times this instead Forbidden (CSRF token missing or incorrect.): /formtest [07/May/2020 02:28:44] "POST /formtest HTTP/1.1" 200 4 django version 2.0.5, python version 3.6.5 -
Delete posts on profile django
I have been working on a project and one of the functions that it has it to delete posts, when in the imagelist view, I am able to delete those posts but when I am in the profile view which shows the user's posts when I try to delete it, a 404 error page not found shows up. I dont know where the error is but I think it is on the profile view. views.py def profile(request, pk=None): if pk: post_owner = get_object_or_404(User, pk=pk) user_posts=Post.objects.filter(user_id=pk) else: post_owner = request.user user_posts=Post.objects.filter(user_id=pk) return render(request, 'profile.html', {'post_owner': post_owner, 'user_posts': user_posts,}) profile.html <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ post_owner.username }}</h2> <p class="text-secondary">{{ post_owner.email }}</p> </div> </div> <div> {% for Post in user_posts %} <li class="list-group-item">{{ Post.text }} <a href="{% url 'profile_pk' pk=Post.user.pk %}">{{ Post.user }}</a> {% if Post.posti %} <img src="{{ Post.posti.url }}" alt="image here" style="max-width: 300px; max-height: 300px"> {% endif %} {% if Post.user == user %} <div class="float-right"> <form action="delete_image/{{ Post.id }}/" action="post"> <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button> </form> </div> {% endif %} </li> {% endfor %} </div> </div> urls.py urlpatterns = [ path('profile/<int:pk>/', views.profile, name='profile_pk'), path('imagepost', views.uimage, name='image'), path('imagelist', views.imagelist, name='imagelist'), path('delete_image/<int:image_id>/', views.delete_image, … -
Django doesn't recognize CSS import variables
I have two CSS files in my static folder. One is called typography.css. This CSS file has @import url("variable.css") where multiple variables are stored. How do I get Django to recognize the variable.css file? -
Django Database Structure for Users in Teams
This is probably a very easy question. I want to create the following functionality in django. Someone can create a team and add people to the team. So, at any point, there could be several teams with several users in them. The team data structure has CRUD capabilities. Kind of like github teams. What would be the best database structure for this? I know there are many ways - so what are the advantages and disadvantages of each way?! New to this so really appreciate any questions. -
Django how to not change address while changing the results
I am designing calendar application using Django. It has calendar, and next/prev month button to move between months. But if I connect a views to the buttons, URL changes each time I click on it : If I click prev month button, the url will be something like this : http://my.site/prev_month But I want to just refresh the calendar not changing the address, after clicking the buttons. Is there way I can solve my problem? thanks. -
Django - OneToOneField keeps returning None
My OneToOneField Keeps returning None. I try to go to my site so a form can automatically put the author of the post as the current logged in person. I looked around and saw OneToOneField could do this. It keeps returning None when I in fact have Users in the User model. What on Earth is going on? Models.py: - This is where the main problem is happening from django.db import models from datetime import datetime from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.conf import settings from django.contrib.auth import get_user_model class MainPost(models.Model): post_author = models.OneToOneField(User, on_delete=models.CASCADE) post_title = models.CharField(max_length=200) post_content = models.TextField() post_published = models.DateTimeField("date published", default=datetime.now()) def __str__(self): return self.post_title class MainPostForm(ModelForm): class Meta: model = MainPost fields = ["post_title", "post_content", "post_author"] readonly_fields = "post_published" Views.py - The Important thing is create_request() at the bottom from django.shortcuts import render, redirect from django.shortcuts import render, redirect from django import forms from django.http import HttpResponse from django.views.generic import CreateView from django.contrib.auth.forms import AuthenticationForm from .models import MainPost, MainPostForm from .forms import NewUserForm from django.contrib import messages from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User from datetime import datetime def homepage(request): return render(request, template_name="trymysite/home.html", … -
django-channels 1.x detect when user leaves/refreshes page
How can I detect this? Currently I can only do_something if the user clicks a back button and I manually disconnect from the websocket under consideration. Sometimes Websocket DISCONNECT fires, but much of the time it doesn't. If a user refreshes or leaves a page, the disconnect code cannot run. How can I detect when a user leaves/refreshes? -
Callable to add to list_display that references extra field in the intermediary model of a M2M relationship
I have two models, Tender and Status, that have a many-to-many relationship with an intermediary model TenderStatus. TenderStatus has an extra date field which denotes the date on which each status was applied. I want to show all the statuses for each Tender in the list_display. I understand that I have to create a callable in my TenderAdmin class to include in list_display, and although I am able to list out the statuses, I'm having trouble accessing the date field in the intermediary model. Here's an abbreviated version of my models.py: class Tender(models.Model): name = models.CharField( max_length=255, null=False ) tender_status = models.ManyToManyField( 'Status', through='TenderStatus', related_name='tender_status' ) class Status(models.Model): status = models.CharField( max_length=50, null=False ) class TenderStatus(models.Model): tender = models.ForeignKey('Tender', on_delete=models.DO_NOTHING, blank=True, null=False) status = models.ForeignKey('Status', on_delete=models.DO_NOTHING, null=False) date = models.DateField(blank=True, null=False) And here's an abbreviated admin.py--note the status_list callable, this one works but it doesn't have the date in there. Any attempts I've made to access the date have not worked. class TenderAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = ['name', 'status_list'] def status_list(self, obj): return [x.status for x in obj.tender_status.all()] status_list.allow_tags = True I've tried this, but it can't find the date and returns a 500 error: def status_list(self, obj): return [str(x.date) + … -
Django Crispy_forms doesn`t load the correct layout
I spent a few hours trying to debug this error but could not find out why. I don`t have any errors message. I would like to display my form in two columns using the crispy forms layout. Goal: Display the forms with the layout defined in the forms.py file Issue: The layout doesn`t display as expected and list all fields on different lines. forms.py from crispy_forms.helper import FormHelper from .models import Project from django.core.exceptions import ValidationError from crispy_forms.layout import Layout, Submit, Row, Column, ButtonHolder class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['type','chantier','customer','contact'] def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) helper.form_method = 'POST' Row( Column('type', css_class='form-group col-md-6 mb-0'), Column('chantier', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Row( Column('customer', css_class='form-group col-md-6 mb-0'), Column('contact', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) Createproject.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy form %} {% block body %} <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} </form> {% endblock %} Many Thanks -
what am I doing wrong at the moment to validate my lesson class?
I want to validate if my lesson material belongs to a xyz user with pro right it will show the correct conent, but if not it will display become a member , but however I am getting if I change id membership to pro or vice versa it always true the statement def get(self, request): template = loader.get_template(self.template_name) template_member = loader.get_template(self.template_payment) #rendering the template in HttpResponse lesson = Lesson.objects.first() user_membership = UserMembership.objects.filter(user=self.request.user).first() user_membership_type = user_membership.membership.membership_type lesson_allowed_mem_types = lesson.allowed_memberships.all() if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists(): return HttpResponse(template.render()) else: return HttpResponse(template_member.render()) models class Lesson(models.Model): allowed_memberships = models.ManyToManyField(Membership) class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user.email -
Custom User model in django. UNIQUE constraint failed: users_user.username
I am trying to make a custom registration form. Main idea is that users should use email as login method and be able to set username in profile(so I dont want to override username field). Problem with built-in django User model is that username field is required so I made my own model based on AbstractUser. Now when I am trying to register a new user I get "UNIQUE constraint failed: users_user.username". models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass forms.py from django import forms from .models import User class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=100, required=False) email = forms.EmailField(label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'email@example.com'})) password = forms.CharField(label='', max_length=100, widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) class Meta: model = User fields = ['username', 'email', 'password'] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import RegisterForm def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('trade') else: form = RegisterForm() return render(request, 'users/register.html', {'form': form}) AUTH_USER_MODEL = 'users.User' is set I tried to set email unique=True in models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True) Now I get "The view users.views.register didn't return an HttpResponse object. It returned None instead" instead. … -
Django urls and views properly defined, still showing 404 error
I have a blog which was running without any error. Different users can register, login, and post articles. Users can write/edit/delete comments on the articles. Previously, the URL of the articles were decided using 'article id'. Later, I read this tutorial and added slug along with id in the URL for every article's Detail View. Then I deleted my old articles since they didn't have any slugs. After this change, a user can create a comment successfully, but cannot 'edit' or 'delete' any comment. Whenever 'edit' or 'delete' button is pressed, 404 error is shown. See the error image by pressing this link. Page not found (404) Request Method: GET Request URL: http://localhost:8000/articles/33/comment_edit/ Raised by: articles.views.ArticleDetailView No article found matching the query My corresponding files are listed below: urls.py (inside Articles App directory) from django.urls import path from .views import (ArticleListView, ArticleUpdateView, ArticleDetailView, ArticleDeleteView, ArticleCreateView, CommentCreateView, CommentUpdateView, CommentDeleteView) urlpatterns = [ path('', ArticleListView.as_view(), name='article_list'), path('<int:pk>/<str:slug>/edit/', ArticleUpdateView.as_view(), name='article_edit'), path('<int:pk>/<str:slug>/', ArticleDetailView.as_view(), name='article_detail'), path('<int:pk>/<str:slug>/delete/', ArticleDeleteView.as_view(), name='article_delete'), path('new/', ArticleCreateView.as_view(), name='article_new'), #Comments below path('<int:pk>/<str:slug>/comment/', CommentCreateView.as_view(), name='comment_new'), path('<int:pk>/comment_edit/', CommentUpdateView.as_view(), name='comment_edit'), path('<int:pk>/comment_delete/', CommentDeleteView.as_view(), name='comment_delete'), ] I have tried and run the website by commenting out the url for comments, i.e., the last three lines above. The error … -
Gunicorn not loading environment file
I have a gunicorn service file that looks like this [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=afrinovate-admin Group=www-data EnvironmentFile=/etc/afrinovate/gunicorn.env WorkingDirectory=/home/afrinovate-admin/afrinovate ExecStart=/home/afrinovate-admin/.local/share/virtualenvs/afrinovate-VhxtDRfD/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ afrinovate.wsgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target But when i try starting gunicorn i get this error about not SECRET_KEY empty, which is in the EnvironmentFile specified in the gunicorn file. File "/home/afrinovate-admin/.local/share/virtualenvs/afrinovate-VhxtDRfD/lib/python3.7/site- May 06 20:54:25 afrinovate-test-api gunicorn[7293]: raise ImproperlyConfigured("`enter code here`The SECRET_KEY setting must not be empty.") May 06 20:54:25 afrinovate-test-api gunicorn[7293]: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
Django 3.0: Unable to get username in template
I have issue is that in template, I automatically get access of username of Superuser (if that is logged-in) but not username of user based on Buyer (Model). User is getting registered and also can login (I can see it in database). But in template I am unable to get username of user other than superuser. I don't what i am missing here. So i am putting all code of view.py here. Also after user logging he sees bookrepo:home and i am using user logic in header.html (bookrepo:home extends header.html) I have model named Buyer in models.py file. And based on this model, two modelForm has made. This is code of model.py class Buyer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # additional attributes contact = models.CharField('Contact #', max_length=16, unique=True, validators=[ RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number (Up to 15 digits) must be entered in the format: '+923001234567'." ), ], ) devices = models.CharField('Devices', unique=False, max_length=115, blank=True) picture = models.ImageField(upload_to=profile_pic_path, null=True,blank=True) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) class Meta: get_latest_by = '-user.date_joined' This is code of modelForms class RegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username', 'email', 'password') def clean(self): cleaned_data = super(RegistrationForm, … -
DRF-Filtering with multiple query params and foreign keys
I'm new to Django and I'm trying to create a route that can be called to retrieve an array of vehicles from my database, but I want the user to be able to provide multiple query params in the url (something like: http://127.0.0.1:8000/vehicles/?year=2020&make=Toyota). The problem that I have come across is that my vehicle model includes references to foreign keys for the make and the v_model (so named to avoid conflict with the Django "model"). I have a solution that doesn't seem very graceful. The fact that I have three nested conditional statements for each search field makes me suspicious. I tried using "filters.SearchFilter" but I was only able to provide a single value on which to base the search. So a request like this: http://127.0.0.1:8000/vehicles/?search=2020&search=Toyota would only search for vehicles with a make of "Toyota", ignoring the "year" parameter. Is there some other way to do this that is cleaner or more "Django-approved"? Here is my code: models.py: class Make(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name class VModel(models.Model): name = models.CharField(max_length=200, unique=True) make = models.ForeignKey(Make, on_delete=models.CASCADE) def __str__(self): return self.name class Vehicle(models.Model): make = models.ForeignKey(Make, on_delete=models.CASCADE) v_model = models.ForeignKey(VModel, on_delete=models.CASCADE) year = models.CharField(max_length=5) def __str__(self): return self.year … -
Django form wokrs first time but not the rest
I have a Django form to filter a queryset. I use a MultipleChoiceField there. The first time I execute the form it works fine but after that it looks like it has all the options checked. I added a message line within the form part in the view only if I have both values. The second time I run the form it gets printed. Thanks in advance! The Form class FilterEmpresaFulbergForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FilterEmpresaFulbergForm, self).__init__(*args, **kwargs) self.fields['Nombre'].required = False self.fields['pais'].required = False self.fields['company_type'].required = False company_type = ( ('Client', 'Client'), ('Supplier', 'Supplier'), ) mis_clientes = forms.BooleanField(required=False, initial=False, label='Extra cheeze') company_type = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=company_type, required=False) class Meta: model = Contactos_Fulberg fields = ('Nombre', 'pais') def save(self, commit=True): return super(FilterEmpresaFulbergForm, self).save(commit=commit) The view @login_required def EmpresasFulbergView(request): page_title = str("Empresas") now = date.today() - timedelta(days=365) filter_form = FilterEmpresaFulbergForm(request.POST) empresa_form = EmpresaFulbergForm(request.POST) if request.user.groups.filter(name="Dirección").exists() or request.user.groups.filter(name="Comex").exists(): all_contact = Contactos_Fulberg.objects.all() else: all_contact = Contactos_Fulberg.objects.filter(propietario=request.user) total_listado = all_contact.count() alerta_desde = date.today() - timedelta(days=90) if request.method == "POST" and 'filtro' in request.POST: filter_form = FilterEmpresaFulbergForm(request.POST) if filter_form.is_valid(): Nombre = filter_form.cleaned_data['Nombre'] if Nombre: all_contact = all_contact.filter(Nombre__icontains=Nombre) pais = filter_form.cleaned_data['pais'] if pais: all_contact = all_contact.filter(pais__icontains=pais) mis_clientes = filter_form.cleaned_data['mis_clientes'] if mis_clientes: all_contact = all_contact.filter(propietario=request.user) company_type = filter_form.cleaned_data['company_type'] if … -
How to perform a post request on django restframework viewset.ViewSet
I am trying to perform a post request using axios to my django backend. It's giving me an error 401 Unauthorized. JavaScript Frontend saveArticle(){ let that = this; axios .post("http://localhost:8000/api/articles/", { headers: { Authorization: `Bearer ${that.$store.getters.accessToken}` }, title: that.title, content: that.content }) .then(response => { console.log(response) }); } Python Backend class ArticleViewSet(viewsets.ViewSet): """ API endpoint that allows articles to be viewed or edited """ def list(self, request): queryset = Article.objects.all().order_by('-date') serializer = ArticleSerializer(queryset, many=True) return Response(serializer.data) #Getting one article by providing it's id def retrieve(self, request, pk=None): queryset = Article.objects.all() article = get_object_or_404(queryset, pk=pk) serializer = ArticleSerializer(article) return Response(serializer.data) #Create new article def create(self, request): print(request.user) return Response({"message": "Article saved"}) #Edit article def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): queryset = Article.objects.all() article = get_object_or_404(queryset,pk=pk) article.delete() return Response({"message": "Deleted"}) def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires """ if self.action == 'list': permission_classes = [permissions.IsAuthenticated,] if self.action == 'create': permission_classes = [permissions.IsAuthenticated,] else: permission_classes = [permissions.IsAdminUser,] return [permission() for permission in permission_classes] I am using JWT tokens to authenticate. Listing the articles is working but posting data to create one is not working. I am not really … -
Passing a dictionnary in a template in Django
I need to pass a dictionnary which I generate in my views.py to my template in Django. template {% for server in servers %} <div class="hs-item set-bg" data-setbg="{% static 'img/slider-1.jpg' %}"> <div class="hs-text"> <div class="container"> <h2>The Best <span>Games</span> Out There</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada <br> lorem maximus mauris scelerisque, at rutrum nulla dictum. Ut ac ligula sapien. <br>Suspendisse cursus faucibus finibus.</p> <a href="#" class="site-btn">Read More</a> </div> </div> </div> {% endfor %} views.py def get_data(request, server_name): server=Server.objects.get(Name=server_name) address = (server.IP, server.Port) connect = "steam://connect/"+str(server.IP)+":"+str(server.Port) queryset=a2s.info(address, timeout=3.0, encoding=None) max_player=queryset.max_players current_player=queryset.player_count current_map=queryset.map_name playerdata={ 'map': current_map, 'players': current_player, 'adress': connect, 'max': max_player, } return HttpResponse(playerdata) models.py class Server(models.Model): Name = models.CharField(max_length=100) IP = models.TextField() Port = models.IntegerField() Image = models.ImageField(default='default.jpg', upload_to='server_pics') def __str__(self): return str(self.Name) if self.Name else '' What I'm trying to do here, is to loop over all the servers in my template, then, for each server, query said server using a python script, putting the value in a dictionnary, i.e player_count, current_map, etc, then displaying those informations in my template. My problem is that, i don't know how to return said dictionnary to the template. I've already done something similar by using ChartJS, using JsonResponse … -
I'm suddently not able to run server manage.py django since I upgrade my PyCharm
I can run server to test my webapp. Since I upgrade my PyCharm I cant run it. I dont know how to do Bellow is the error output Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 598, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 583, in start_django reloader.run(django_main_thread) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 301, in run self.run_loop() File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 307, in run_loop next(ticker) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 347, in tick for filepath, mtime in self.snapshot_files(): File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 363, in snapshot_files for file in self.watched_files(): File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 262, in watched_files yield from iter_all_python_module_files() File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 139, in iter_modules_and_files if not path.exists(): File "C:\Users\migue\AppData\Local\Programs\Python\Python35-32\lib\pathlib.py", line 1291, in exists self.stat() File "C:\Users\migue\AppData\Local\Programs\Python\Python35-32\lib\pathlib.py", line 1111, in stat return self._accessor.stat(self) File "C:\Users\migue\AppData\Local\Programs\Python\Python35-32\lib\pathlib.py", line 371, in wrapped return strfunc(str(pathobj), *args) OSError: [WinError 123] … -
How to convert Python List of numbers to json object
I want to convert python list of numbers to a json object. input: my_list = [22,30,44,55] output: { "budget" : 22, "budget" : 30, "budget" : 44, "budget" : 55 }