Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
assertRedirects(response) triggers NoReverseMatch error;
I'm testing a scenario where a User successfully edits an answer in response to a question. Once the answer is edited, the user is redirected to a listing page with the question and all answers posted. The problem being encountered is that the user is not being redirected; a NoReverseMatch error is being raised: Reverse for 'question' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['questions/(?P<question_id>[^/]+)/$'] self.assertRedirects() is trigger this error within in the test. Yet, I cannot pinpoint why it's being raised when question_id is being passed into the reverse("posts:question", kwargs={"question_id": answer.question.id}) call of assertRedirects()? It's saying that the key is 'id'? class TestEditInstanceAnswerPage(TestCase): '''Verify that a User who has posted an Answer to a given Question has the ability to edit their answer.''' @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user("TestUser") cls.profile = Profile.objects.create(user=cls.user) cls.answer_user = get_user_model().objects.create_user("TheAnswer") cls.answer_profile = Profile.objects.create(user=cls.answer_user) cls.tag = Tag.objects.create(name="Tag1") cls.question = Question.objects.create( title="How do I get an answer to my post", body="This is the content that elaborates on the title that the user provided", profile=cls.profile ) cls.question.tags.add(cls.tag) cls.answer = Answer.objects.create( body="This is an answer in response to 'How do I get an answer to my post'", question=cls.question, profile=cls.answer_profile ) cls.data = { "body": "This … -
django-elasticsearch-dsl Object of type 'AttrList' is not JSON serializable
I have a Django application where I need to implement a search system, for this application, elasticsearch seems to be the most suitable, but I came across a problem that I can't solve. I have in postgres a table with a column of type jsonb similar to this: [ { "act": 1900, "max": 2850, "min": 2850, "tgt": 2850, "desc": "L - Durchsatz (kg/h)", "name": "L - Durchsatz (kg/h)", "unit": "kg/h", "color": "red", "ordering": 1, "monitoring": true }, { "act": 283, "max": 425, "min": 425, "tgt": 425, "desc": "L - Siebbandgeschwindigkeit (m/min)", "name": "L - Siebbandgeschwindigkeit (m/min)", "unit": "m/min", "color": "red", "ordering": 2, "monitoring": true }, ... ] Django Model: class Collect(models.Model): recipe = models.ForeignKey(RecipeSentHistory, on_delete=models.CASCADE, null=True, default='1') general_info = models.JSONField(default=dict) record = models.JSONField(default=dict) justify = models.CharField(max_length=255, default='*') automatic = models.BooleanField(default=False) user = models.CharField(max_length=255, default='*') user_job_position = models.CharField(max_length=255, default='*') timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return self.recipe.machine.name My serializer: class MyCollectSerializer(serializers.ModelSerializer): class Meta: model = Collect fields = [ 'justify', 'record', 'user', 'user_job_position', 'timestamp', 'automatic', 'recipe_id', 'general_info', ] read_only = True My documents.py: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from mpa.models import Collect @registry.register_document class CollectDocument(Document): general_info = fields.ObjectField( properties={ 'batch': fields.TextField(), 'machine': fields.TextField(), 'recipe_cep': fields.TextField(), 'recipe_mpa': fields.TextField(), 'fabrication_order': … -
Django: How to store certain objects of a model in another model
I am currently trying to create a user profile that will contain the courses that the user chose. Currently, the user profile model is UserProfile and the courses are objects of Course. I've tried using the ManyToMany field but that just results in UserProfile storing all courses in Course. The two models are stored in different apps. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") courses = models.ManyToManyField("course.Course", blank=True, default=None, related_name = "courses") def __str__(self): return f"{self.user.username} Profile" Any help is appreciated. Thanks. -
How can I get the total objects returned in Django queryset within my aggregation?
If I have a model: class Book(models.Model): name = models.CharField(max_length=100) ... And I do a query: Book.objects.filter(name__icontains="The").aggregate(number_of_books=Count("*"), ...) Here, I'm filtering the books to only return ones that contain the The substring, and doing an aggregation. I want the resulting dict to tell me, among other things, how many items were in my queryset. This should be the same as if I did Book.objects.filter(name__icontainers="The").count(). What will get me the total number of items (Books) in my queryset? Count("*") was just a guess, but it seems to work. Is that correct? -
How to create an API using django
I need to create an API using django. My api should call a query that I have created . Here is the code of my query : import pymongo from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") db = client['db3']['aliex3'] dbColumn = db["comments"] query = { "Feedback.country": "MA" } docs = dbColumn.find(query) for x in docs: print(x) My query select from my mongodb database comments that are from country x. My API takes as imput this country and give as output list of comments with this country. This is my database schema : { "_id": { "$oid": "624718162b554a6ec1efb625" }, "Title": "Original TWS Y50 Fone Bluetooth Headphones Sports Outdoor Wireless Earphones Touch Control Headset with Charging Box Y50 Earbuds ", "Price": "37.69", "Currency": "MAD", "Stars": "4.7", "Orders": "1066 sold", "Shipcost": "Free Shipping", "Supplier": "Shop5524084 Store", "Productlinks": "https://www.aliexpress.com/item/1005003705651241.html?algo_pvid=c95de82c-2500-44f3-998b-ddd2c220d3fa&algo_exp_id=c95de82c-2500-44f3-998b-ddd2c220d3fa-0&pdp_ext_f=%7B%22sku_id%22%3A%2212000026872977176%22%7D&pdp_pi=-1%3B37.69%3B-1%3B-1%40salePrice%3BMAD%3Bsearch-mainSearch", "Feedback": [ { "country": "LK", "comment": "ok", "images": [] }, { "country": "PK", "comment": "order received on the time, with great quality.", "images": [ "https://ae01.alicdn.com/kf/Uc5faae18cdd34cba9d4e26d46ae3291eg.jpg" ] }, { "country": "CL", "comment": "excellent", "images": [] }, { "country": "BR", "comment": "Very good", "images": [] }, { "country": "UA", "comment": "Згідно опису. Працює задовільно", "images": [] }, { "country": "BY", "comment": "They work well, they end up … -
JS addEventListener "input" automatically extract what the user typed, I can not reach user Input
Im trying connect JS inside my Django project I got message in console "InputEvent" but I would like to get currency name thats in my wallet I dont know why In this part of code "calculate" I got 2 values curr1 and a1 with out any problems c1[i].addEventListener("change", function() { calculate(curr1,a1); }, false); amount1[i].addEventListener("input", function() { calculate(curr1,a1); }, false); but here c1[i].addEventListener("change", function() { calculate2(curr1); }, false); I received only InputEvent without currency name and also when I use amountAmount.addEventListener("input", calculate2); it works live what the amount put as a input immediately it changes but in here c1[i].addEventListener("change", function() { calculate(curr1,a1); }, false); amount1[i].addEventListener("input", function() { calculate(curr1,a1); }, false); It does not works if I change the amount, nothing happens HERE HOW ITS LOOKS LIKE IN MY WEB BROWSER https://i.stack.imgur.com/BkEEm.png here is the part of html {% extends "web/layout.html" %} {% block body %} <br><br><br> <div id="jumbotron" class="jumbotron" style="text-align: center; margin-top:-50px"> <h1 id="devise" class="display-5">Devise </h1> <h5>Exchange Rate Converter</h5> <img src="image.jpg" class="image" style="width:100px; margin-bottom:-50px; " > </div> <div class="container"> <div class="page-header" id="banner"> <div class="row"> <div class="col-sm-15"> <h1 style="align-content: center;"> </h1> <p class="lead" style="margin-left:280px; font-size:2rem"> </p> </div> </div> </div> <div class="row"> {% for item in buttons %} {% for money_purchased in user_purchased_currencies … -
Django Filter not working with user choosen place
in the code the product is assigned with place, so the products should be come with user choosen place. But now i am getting all the products name with user choosen place also those products are not assigned with any country. def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == ("places","coffee"): kwargs["queryset"] = models.Region.objects.filter( country=request._user_places, ) return super().formfield_for_manytomany(db_field, request, **kwargs) -
heroku python error ' at=error code=H14 desc="No web processes running'
I made a simply website using django and am trying to deploy to Heroku. But I get the following error message when i try to open the web page: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail And this is what i find in the logs: 2022-04-10T18:53:57.509376+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=safe-earth-20673.herokuapp.com request_id=fdb90caf-8174- 4ca3-9871-2046f928c959 fwd="62.163.104.251" dyno= connect= service= status=503 bytes= protocol=https If I use the 'heroku local web' command i get this error: [WARN] ENOENT: no such file or directory, open 'Procfile' [FAIL] No Procfile and no package.json file found in Current Directory - See run-foreman.js -- help And this is what is in my Procfile: web: gunicorn ullie_diary.wsgi --log-file - My Procfile is in the same directory as manage.py. I also have the requirements.txt and runtime.txt files in the same directory. I tried this solution: web: gunicorn ullie_diary.wsgi --log-file - But it doesn't work. I've checked out other questions with the same problem on Stack overflow but can't figure out what the … -
NoReverseMatch at /blog/redirect2
I'm new to django and I've been trying to test the URLs redirection methods I've tried two options but the return render() keeps giving me this error of no reverse match this is my urls.py code : app_name = 'blog' urlpatterns = [ # path('about', views.about, name = 'about'), path('about.html', views.about, name='about'), path('home.html', views.home, name='home'), # path('home', views.home, name ="home") path('redirect', views.redirect_view), path('redirection_fct',views.redirection_fct, name='redir_fct'), #redirection par la fonction as_view path('redirect1', RedirectView.as_view(url='http://127.0.0.1:8000/blog/redirection_fct')), path('redirect2', views.redirect_view1), ] and this is my views file : def about(request): return render(request, 'about.html', {}) def home(request): return render(request, 'home.html', {}) #redirection par HttpResponseRedirect def redirect_view(request): return HttpResponseRedirect("redirection_fct") def redirect_view1(request): return redirect('redir_fct') def redirection_fct(request): return render(request, 'redirection.html', {}) Is there something wrong with my URLs pattern or it is the render one? -
How to check if a relation exists? M2M
I have models: class User(models.Model): ... group = models.ManyToManyField( Group, related_name="users_group", ) class Group(models.Model): .... How to check in serializer is the Group empty (there is no relationship with User) My version is : class GroupSerializer(serializers.ModelSerializer): empty = serializers.SerializerMethodField() class Meta: ... def get_empty(self, obj): return not User.objects.filter(group=obj).exists() But maybe there is an even better way. -
I got an error when installing django-pyqt library
I tried to install the django-pyqt library using the following command PS C:\Windows\system32> py "C:\Users\mehdi\Desktop\myfiles\python\git hub\django-pyqt-master\django-pyqt-master\setup.py" but i got this Error PermissionError: [WinError 5] Access is denied: 'C:\Users\mehdi\.django-pyqt\drivers\etc\hosts' I followed the installation method exactly from the site and I will put the link below https://github.com/ZedObaia/django-pyqt -
Unable to read environment variables in Django using django_configurations package
I was using django-environ to manage env variables, everything was working fine, recently I moved to django-configurations. My settings inherit configurations.Configuration but I am having trouble getting values from .env file. For example, while retrieving DATABASE_NAME it gives the following error: TypeError: object of type 'Value' has no len() I know the below code return's a value.Value instance instead of a string, but I am not sure why is that behaviour. The same is the case with every other env variable: My .env. file is as follows: DEBUG=True DATABASE_NAME='portfolio_v1' SECRET_KEY='your-secrete-key' settings.py file is as follows ... from configurations import Configuration, values DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': values.Value("DATABASE_NAME", environ=True), ... I have verified that my `.env' file exists and is on the valid path. Any help would be appreciated. -
Can someone explain why my form fields are dissappering when they are not being selected?
Image of Form Fields Dissapeering When Not Selected Hi all, I am having trouble understanding why my fields are disappearing when they are not selected. I am rendering this form using Crispy Forms (followed via Youtube Tutorial). This feature was working earlier - however, I am not sure why it suddenly stopped working. I have a few other forms in this application and they are facing the same issue. Here is the relevant code that is being used to generate the form class BookAppointmentForm(forms.ModelForm): class Meta: model = BooksAppt fields = '__all__' labels = { 'hp_username': 'Doctor', 'appt_date': 'Appointment Date', 'p_username': 'Patients' } widgets = { 'appt_date': forms.TextInput(attrs={'type': 'date'}) } def __init__(self, p_username=None, *args, **kwargs): super(BookAppointmentForm, self).__init__(*args, **kwargs) if p_username: self.fields['p_username'].queryset = Patient.objects.filter( p_username=p_username).values_list('p_username', flat=True) Relevant HTML being used to render the form <div class="container" style="background-color:#E6E6FA"> <div class="col-md-10 offset-md-1 mt-5"> <div class="card-body"> <h1 class="display-5 "> Booking an Appointment for {{ user }}</h1> <p class="lead">Please Fill in the Following Form to Register an Appointment</p> <hr class="my-4"> <form class="register" action="" method="post" autocomplete="off"> {% csrf_token %} {{ form.errors }} {{ form.non_field_errors }} {{ form.p_username|as_crispy_field}} {{ form.hp_username|as_crispy_field }} {{ form.appt_date|as_crispy_field }} <button type="submit" class="btn btn-success">Submit</button> </form> <br> </div> </div> I feel as though the … -
how to show description under choies in django
I want to show small description under choies like this image, in front to need to pass this value to show description,any can help me my model is from django.db import models from sqlalchemy import true from company.models import Company from django.contrib.auth.models import User WORK_PLACE_TYPE =( ('onsite',' On-site'), ('hybrid','Hybrid'), ('remote','Remote'), ) class Job(models.Model): company =models.ForeignKey(User, on_delete=models.CASCADE); title = models.CharField(max_length=200) description = models.TextField(max_length=1500) date = models.DateTimeField(auto_now_add=true) workplace_type = models.CharField(max_length=32 , choices=WORK_PLACE_TYPE ,default='onsite',) experience =models.CharField(max_length=400) skills =models.CharField(max_length=200) location =models.CharField(max_length=100) def __str__(self): return '{} {} {} '.format(self.title,self.company,self.location) Any hint how to do this. -
Django Problem to access to template file.html
I write like this ** in Views :** def index(request): return render(request,'Expenses/index.html') def add_expenses(request): return render(request,'Expenses/add_expenses.html') ** in Project Urls :** from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include('expenses.urls')), path('admin/', admin.site.urls) ] ** in application Urls :** urlpatterns = [ path('',views.index, name='expenses') , path('add_expenses',views.add_expenses, name='add_expenses') ] but I when I run the project I had a problem Like that -
Django how to add previous button for related blog post?
I added next button but can’t figure how to add previous button. I added parent from my first object to before last one. see the layout for better understood blog title parent object next button (python tutorial - 1 )---->(python tutorial-2)----- >successfully added next button (python tutorial-2 )------>(python tutorial-3)----- >successfully added next button (python tutorial-3)-------> Null-------> No button as no parent my html: {{i.blog_title}} {{i.blog_parent.title}} {%if i.blog_parent %} <a href="{% url 'blog:blogDetails' i.blog_parent.blog_slug %}" id="next_button">next_button</a> {%endif%} {%endfor%} Now I want to add previous button from my second blog post to last blog post. How to do that? any idea? -
How to pass inMemoryUploadedFile into an api
I want to pass user uploaded images into an api from my view I have this form which submits a file into view <form action="http://127.0.0.1:8000/handler/" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit"> </form> I want to again send this file into an api but I can't do it directly, I think i must convert the file into string and pass to the api. Anybody have any idea on how to do it @csrf_exempt def handler(request): if request.method == 'POST': file = request.FILES['file'] res = requests.post('http://192.168.1.68:8000/endpoint/',{}) -
Django form.is_valid() return flase all time
the function form.is_valid() return flase all time and i dont understand why. pliz help meץ Thanks for all the answers. views.py views.py html file html file -
How to edit ManyToManyField in model's save() method?
I have a method which has a required field for the author and a non-required field for co-authors. Sometimes the person which creates the post unintentionally, or because of the lack of knowledge, selects his/her own profile as a co-author. I would like to remove the actual author from the co-authors, and I think the best way to do it is overriding model's save() method. Here's what I have so far, but it doesn't seem to work. models.py from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ User = get_user_model() class Post(models.Model): PUBLICATION_STATUS_CHOICES = [ ("PUBLIC", _("public")), ("PRIVATE", _("private")), ("DRAFT", _("draft")), ] title = models.CharField(max_length=100, verbose_name=_("post title")) summary = models.CharField(max_length=250, verbose_name=_("post summary")) content = models.TextField(verbose_name=_("post content")) is_markdown = models.BooleanField(default=True, verbose_name=_("Markdown"), help_text=_("Is this a post written in Markdown format?")) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts", verbose_name=_("author of the post")) coauthors = models.ManyToManyField(User, blank=True, related_name="colab_posts", verbose_name=_("colaborators / co-authors")) date_created = models.DateTimeField(default=now, verbose_name=_("date of creation")) date_updated = models.DateTimeField(default=now, verbose_name=_("last update")) status = models.CharField(max_length=10, choices=PUBLICATION_STATUS_CHOICES, default=PUBLICATION_STATUS_CHOICES[0][0], verbose_name=_("post status")) slug = models.SlugField(unique=True, verbose_name=_("slug")) class Meta: ordering = ["-date_created"] verbose_name = _("post") verbose_name_plural = _("posts") def __str__(self): return f"{self.title} ← {self.author} ({self.date_created.strftime('%Y-%m-%d %H:%M:%S')})" def … -
How can I change the default register mutation in django-graphql-auth?
I want to change the fields of register mutation for example I want to ask for the password only once , and also I want do add extra fields like first_name , last_name, date_of_birth ... all of that , but still I want to beneficiate the use of the email verification and all the good parts that djang-graphql-auth brings . So here is what I have right now : A custom user (I only want the user to login using the email) : from django.db import models from django.contrib.auth.models import AbstractUser class ExtendUser(AbstractUser): email = models.EmailField(blank=False, max_length=255, unique=True, verbose_name="email") date_of_birth = models.DateField(blank=False, null=True, verbose_name="date_of_birth") # phone = # country = city = models.CharField(blank=True, max_length=150, verbose_name="city") company_name = models.CharField(blank=False, max_length=150, verbose_name="company_name") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # USERNAME_FIELD = "username" EMAIL_FIELD = "email In my schema.py I have the following : import graphene from graphene_django import DjangoObjectType from .models import ExtendUser from graphql_auth import mutations from graphql_auth.schema import UserQuery, MeQuery class UserType(DjangoObjectType): class Meta: model = ExtendUser fields = ("id", "first_name", "last_name", "email", "date_of_birth", "company_name", "city") class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: first_name = graphene.String(required=True) last_name = graphene.String(required=True) # username = graphene.String(required=True) email = graphene.String(required=True) password = graphene.String(required=True) date_of_birth … -
I am trying to Update my model without a form and show the updated records in a table every time i click on update
I am trying to Update my model and show the updated record in a table every time i click on update. ERROR Reverse for 'subt' with arguments '('',)' not found. 1 pattern(s) tried: ['subt/(?P[0-9]+)$'] Views.py def subs(request, pk): sw = get_object_or_404(Swimmers,id=pk).sessions sw_list = sw sw_lists = sw + 1 context = {'sw_lists':sw_lists} return render(request, 'accounts/modals/swimming/vw_more.html', context) Models.py class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.CharField(max_length=200, blank=False ) dateofpayment = models.CharField(max_length=200, blank=False) phone = models.CharField(max_length=30, blank=False, null=True) date_from = models.DateField(null=True) date_to = models.DateField(null=True) type_choice = ( ("basic", "Basic"), ("3x1 week", "3x1 Week"), ("1 session", "1 Session"), ("2x1", "2x1"), ) type = models.CharField(max_length=200, blank=False, null=True, choices=type_choice, default=type_choice) ammount = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=True) registration = models.DateField(default=timezone.now) keenphone = models.CharField(max_length=30, blank=False, null=True) def __str__(self): return self.name Urls.py path('swimminglist/', views.SWGIndex.as_view(), name="swimminglist"), path('create/', views.SWGCreateView.as_view(), name='create_swimmer'), path('update/<int:pk>', views.SWGUpdateView.as_view(), name='update_swimmer'), path('read/<int:pk>', views.SWGReadView.as_view(), name='read_swimmer'), path('delete/<int:pk>', views.SWGDeleteView.as_view(), name='delete_swimmer'), path('subt/<int:pk>', views.subs, name='subt'), -
Post an image along with text in django restframework with flutter
I am creating a a b2b ecommerce mobile application. I am using flutter as frontend and django for backend. I am stuck while sending a post request to django server with flutter. The case is I have two types of user. THey are seller and buyer. The seller has to post product in the app. model field for product are title, description, price, image. I created post method in django rest framework and it worked while checking through postman. But i am having hard time sending image through flutter. I searched for many things but couldnot figure out what to do. I found articles and videos posting only image at a time but i want to send image along with other text field. How can i do so?? Help me find a solution. -
Ordering in django/dnf by user?
I have model post with field User (FK), can I order all the posts so that the current user's posts come first? For example in serializer class. Or maybe I should write my own filter? -
Django add chat functionality
Hi guys I am currently working on a Django website in which user can sell their old things. Therefore a want that one user can write the user who is offering the product at the moment. I know my question isn't really precise but could you give me a rough overview on how to implement the peer to peer chat functionality. So far I just found tutorials on how to built chat rooms with multiple users which can join this chat and therefore they mainly used Node.js for example. Thanks for your answers. -
django 2FA with yubikey creates wsgi error in login: Timeout when reading response headers from daemon process
Usual 2FA first requires to type your password and then the yubikey token, either when setting it up or when it is already set. I'm using this code:https://github.com/jazzband/django-two-factor-auth When i have to type the yubikey token, i.e., press the yubikey, the information is sent to the database but in the client side the process is not finished (page doesn't go to the next step and browser shows the loading icon but nothing happens until gateway timeout). Nothing works, what I see is that my mysql processlist goes idle (sleep) after the token is typed so it makes me think that the connection with the database is ok. The same code in my localhost with the lightweight django server works fine but in an apache server I have this issue. How could I track down the problem? the error log only says wsgi error, Timeout when reading response headers from daemon process. In my localhost this step gives a 302 response (it works. I believe 302 response is ok with the yubikey). In the production server is 504 (Gateway timeout). Any helps is appreciated