Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'function' object has no attribute 'listings'
I am trying to create an e-commerce site (CS50 Project 2) that allows the user to add and remove listing items to their watchlist. When trying to add a listing, which is a model, to the watchlist model I am receiving this error: 'function' object has no attribute 'listings' which corresponds to this line of code in my views.py: new_watchlist_listing = watchlist.listings.add(listings). The user is able to add the listing item to their watchlist through a Django form with a Boolean Field, and I need help making that field true after the user has added the listing to their watchlist (I want the checkbox that the user sees to be marked so that they can potentially remove the listing from their watchlist). views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) watchlist_form = WatchListForm() #checks if request method is post for all the forms if request.method == "POST": watchlist_form = WatchListForm(request.POST) #checks if watchlist form is valid if watchlist_form.is_valid(): new_watchlist_listing = watchlist.listings.add(listings) WatchList.add_to_watchlist = True return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) models.py class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and … -
Django. How make a handler that opens this link on the server side
I do not know how to properly put the question to find useful articles on google. So here is my problem. I have a hard coded button in my template <a type="button" href="https://api.telegram.org/bot******:*****-*****/sendMessage?chat_id=-******&text=test" class="btn btn-dark w-100 p-3" style="margin-bottom: 16px;">Button 1</a> When you click the link opens and the message after "text= " is sent to messenger. There are two problems with this. The Api token is visible in the inspector. After opening it, the user leaves the site I want to make a handler that opens this link on the server side and redirects the user to the "Successfully Sent" page. What is the easiest way to make it? -
post request in django-react project through mobile
whenever I send data from react to django on same machine it is successful, but when I open that website in mobile , I can not , why? -
How can I best run a daily script that updates my Django App with content from external URLs in Digital Ocean App Platform?
I have a Django Web App set up on the Digital Ocean App Platform. I want to update my Django App daily with content from external URLs. Unfortunately, cron jobs are not available in the App Platform. Specifically, I want to fetch images from external URLs, attempt to download the images, and update it in my Django App if the download was successful. -
Why is it that non-programmers (like my family) can't understand me? [closed]
I understand that such questions are not asked here, but there is professional programmers who have a lot of experience, I hope for a positive response from the community, I am 14 years old, I am not from a very developed country that is far from such concepts as programming, I really like programming, so I started doing it for 3 years and during this time I have gained experience in web full stack programming, but my family does not understand my success, and says that I play for a computer, or fox social networks. How can I explain to them that I'm not wasting my time? -
How to set "verbose_name_plural" variable in metaclass of ModelAdminForm, instead of setting it directly in model's metaclass?
My every single model has metaclass that defines string representation for admin panel, I perform that by setting verbose_name_plural variable: class MyModel(models.Model): ... class Meta: ... verbose_name_plural = "My Representation" I'm sure that this is a very bad approach to set variables directly in model metaclass that are used only inside admin panel. So, I've tried to replace verbose_name_plural into the admin forms metaclasses: class MyModelAdminForm(forms.ModelForm): class Meta: verbose_name_plural = "My Representation" model = MyModel fields = "__all__" class MyModelAdmin(admin.ModelAdmin): form = MyModelAdminForm admin.site.register(MyModel, MyModelAdmin) And this gives no result. How can I perform that, thanks ? -
New django project migrations not reflected in database
I'm attempting to set up a new django project. I am using Adminer for my database GUI and docker for my containers. I have added a model, Notification.py and have created migrations for setting it up on the database. I am able to make this migration within the Docker container without error. On Adminer though, I do not see the Notification table I am creating. I'm including my docker setup here as well, just in case that is the culprit. I also attempted to run the SQL directly in Adminer: root@65787223f662:/mos-nss# python manage.py sqlmigrate main 0001 BEGIN; -- -- Create model Notification -- CREATE TABLE "main_notification" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "sender_id" integer NOT NULL, "receiver_id" integer NOT NULL, "notification_group_id" integer NOT NULL, "notification_type" varchar(255) NOT NULL, "date_created" datetime NOT NULL, "is_deleted" bool NOT NULL); COMMIT; ... which results in an error when I copy and paste the auto-generated query and run it: Error in query (7): ERROR: syntax error at or near "AUTOINCREMENT" LINE 1: ..._notification" ("id" integer NOT NULL PRIMARY KEY AUTOINCREM... Trace from my terminal while making migrations: root@65787223f662:/mos-nss# ./manage.py makemigrations main Migrations for 'main': main/migrations/0001_initial.py - Create model Notification root@65787223f662:/mos-nss# python manage.py migrate main … -
Repeat functions 500 per day
Hi i want to make program.how can i repeat a function 500 times per day? please answer me with an example.I have used time module and loop command.This is my example: import schedule import time def job(t): print "I'm working...", t return schedule.every().day.at("01:00").do(job,'It is 01:00') while True: schedule.run_pending() time.sleep(60) -
ckeditor not saving changes django
I have a form where in one of the fields, I use the ckeditor. However when I submit the form, the changes in the ckeditor field is not being saved. In the model, I have changed the field to aRichTextField. I have installed "ckeditor" in my apps in settings as well. I have also both tried to load these scripts in my template: {% load static %} <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> On top of that have I also tried to add the {{ form.media }} instead of the scripts but it does still not work. I am using HTMX to dynamically update the form. This is my form template right now <form action='' method="POST" class="form" hx-post='' hx-swap='outerHTML'> {% csrf_token %} {{ form.media }} <div class="form-group"> {% for field in form %} {{ field }} </div> {% endfor %} <br> <div class='htmx-indicator'>Loading...</div> <div class="text-center"> <button class='htmx-inverted-indicator' type='submit' >Save</button> </div> {% if message %} <p>{{ message }}</p> {% endif %} </form> Does anybody know why the form is not being saved? -
Django how to annotate in prefetch_related
I have three models: class User: screen_name = Charfield class Post: author = FK(User) class Comment: post = FK(Post, related_name=comment_set) author = FK(User) Now I want to annotate Posts in following way (original annotation is more complicated, added simpler example): comment_qs = Comment.objects.annotate( comment_author_screen_name_seen_by_user=F("author__screen_name") ) queryset = queryset.annotate( post_author_screen_name_seen_by_user=F("author__screen_name") ) queryset = queryset.prefetch_related(Prefetch("comment_set", queryset=comment_qs)) After this I want to filter Posts by comment_set__comment_author_screen_name_seen_by_user field, but I receive following error: django.core.exceptions.FieldError: Unsupported lookup 'comment_author_screen_name_seen_by_user' for AutoField or join on the field not permitted But this field can be accessed: queryset[0].comment_set.all()[0].comment_author_screen_name_seen_by_user == "Foo Bar" I thing something wrong with Prefetch, but can't tell what exactly. Any thoughts? -
command not found: django-admin
I have downloaded anaconda and Django, but VS code shows ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? so, I check out Get out of root conda environment and Problem with django after installing anaconda, installed django in virtual environment. Then follow https://docs.djangoproject.com/en/4.0/topics/install/. But I can't check out version by''' django-admin.py --version''' it shows command not found: django-admin -
Is it possible to save the same form multiple times in Django views.py?
I appreciate this is a bit of an odd request. Depending on the text entered, I want to save the same form a certain number of times. I have the following in my views.py def notes(request): note_form = NoteForm note_form=NoteForm(request.POST) if note_form.is_valid(): new_note = note_form.save(commit=False) new_note_parse = new_note for x in range(2): new_note_parse.save() return HttpResponseRedirect(reverse('notes:notes')) -
Django not able to acces slug - comment_create() got an unexpected keyword argument 'slug'
I am trying to create a comment section under a url with slug:slug using the following code, the error comment_create() got an unexpected keyword argument 'slug' pop up views.py class MovieDetail(DetailView): model = Movie def get_object(self): object = super(MovieDetail, self).get_object() object.views_count += 1 object.save() return object def get_context_data(self, **kwargs): context = super(MovieDetail, self).get_context_data(**kwargs) context['links'] = MovieLinks.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(category=self.get_object().category) return context @login_required(login_url='/accounts/login') def add_comment(request, pk): movie = Movie.objects.get(id=pk) form = CommentForm() context = { 'form': form } return render(request, 'add_comment.html', context) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('commenter_name', 'comment_body') widgets = { 'commenter_name': forms.TextInput(attrs={'class': 'form-control'}), 'comment_body': forms.Textarea(attrs={'class': 'form-control'}), } urls.py from django.urls import path from . import views from .views import MovieList, MovieDetail, MovieCategory, MovieLanguage, MovieSearch, MovieYear, CommentForm app_name = 'movie' urlpatterns = [ path('', MovieList.as_view(), name='movie_list'), path('search/', MovieSearch.as_view(), name='movie_search'), path('category/<str:category>', MovieCategory.as_view(), name='movie_category'), path('language/<str:lang>', MovieLanguage.as_view(), name='movie_language'), path('year/<int:year>', MovieYear.as_view(), name='movie_year'), path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'), path('<slug:slug>/add-comment/', views.add_comment, name='add-comment'), ] Please keep in mind i am relatively new to Python and Django.. Whenever I try to manually navigate to my slug/add-comment/ in this case 127.0.0.1:8000/movies/aquaman/add-comment it throws the following error enter image description here -
Tasks are not performed using the admin interface
I use django-celery-beat to create the task. Everything is registered, connected, the usual Django tascas using beat_schedule work. I add a new task, I don't register it in beat_schedule: @app.task def say_hi(): print("hello test") I go into admin, add Periodic tasks, this task in Task (registered) is visible, I select it, I also select the interval every minute and save, Task (registered) is zeroed, and its value appears in Task (custom). The task itself does not start its execution, in the console print is not displayed, but Last Run Datetime is updated in the admin. What could go wrong? -
Django more type of user - ask about advice
I work on my project and i want create 3 type of user include Admin(user and second user with different premission). I want ask which method i should use to do it ? I read a bit about AbstractUser, create group and "flag's" 1th user - will can only add comment/ save file 2th user - will can create model and what 1th have 3th user - admin Admin after 2th get created should get notification that 2th suer get created and he need to accept his perrmision first (before he can create models) -
Django admin TabularInline
All my models are stored in a dedicated database. Django admin is used as "backoffice". The id field is set in all my models : class MyModel(models.Model): id = models.IntegerField(primary_key=True) So for my models i override the save methode in order to use to seq and autoincrement : def save(self, *args, **kwargs): if not self.id : self.id = getNextId("__mymodel_id_seq") super(MyModel, self).save(*args, **kwargs) TabularInLine : class MyModelAdminInline(admin.TabularInline): model = MyModel fields = ['id', 'titre_classe', 'valeur_texte', 'valeur_min', 'valeur_max', 'id_style', 'ordre', 'rayon', 'style_css',] and it is used in an other Admin : MySecondModelAdmin.inlines = [MyModelAdminInline,] With the TabularInline it seems i must set the id manually. If left blank : i get a validation error and the field is shown in red If set readonly : i get the same If not shown in the inline : error too ... -
column "Serviços" is of type character varying[] but default expression is of type integer HINT: You will need to rewrite or cast the expression
My models: class Orcamento(models.Model): id = models.IntegerField(primary_key=True) Cliente = models.CharField(max_length=40, default=0) Cod_Cliente= models.CharField(max_length=40, default=0) N_Orcamento = models.CharField(max_length=40, default=0) Endereço = models.CharField(max_length=50, default=0) Email = models.CharField(max_length=40, default=0) Telefone = models.CharField(max_length=40, default=0) Departamento = models.CharField(max_length=40, default=0) Data = models.CharField(max_length=40, default=0) Revisao = models.IntegerField(default=0) Serviços = ArrayField(models.CharField(max_length=100, default=[])) def __str__(self) -> str: #função para usar o nome do objeto e não a instância return self.Cliente The error: column "Serviços" is of type character varying[] but default expression is of type integer HINT: You will need to rewrite or cast the expression. How can I fiz this? I tryied: Serviços = ArrayField(models.CharField(max_length=100, default='empty')) And doesn't work, same mistake. Please help :/ -
glslCanvas does not recognize shader code via the data-fragment attribute
I'm trying to render a GLSL shader on a Web Application, for which I use glslCanvas. The canvas used for rendering has a data-fragment attribute which is supposed to be able to take a string literal of GLSL code to construct the shader. However, when I use Django context to pass the shader code as the value to that attribute, the shader doesn't seem to work. However, when I instead create a script-tag and load the exact same code via JavaScript, it works. I assume the load function does some kind of formatting that is important for pattern matching, however for my purposes it would be a lot more preferable if I could just use the HTML-attribute. Is that possible? Example shader: #ifdef GL_ES precision mediump float; #endif uniform vec2 u_resolution; uniform vec2 u_mouse; uniform float u_time; // Plot a line on Y using a value between 0.0-1.0 float plot(vec2 st) { return smoothstep(0.02, 0.0, abs(st.y - st.x)); } void main() { vec2 st = gl_FragCoord.xy/u_resolution; float y = st.x; vec3 color = vec3(y); // Plot a line float pct = plot(st); color = (1.0-pct)*color+pct*vec3(0.0,1.0,0.0); gl_FragColor = vec4(color,1.0); } HTML (the script and canvas tags were tested seperately, just put … -
Django test assert not equal
Trying to test selector layer im my app, but django dont pass simle test. Querysets looks quite similar, maybe i lost something. test.py from django.test import TestCase from books.models import Author, Book from books.selectors import get_books class SelectorTest(TestCase): def setUp(self): self.author = Author.objects.create( name='test_author' ) self.book = Book.objects.create( name='test_book', category='Drama', release_date='2001-01-01', author=self.author, is_read=True ) def test_get_books(self): self.assertEqual(get_books(), Book.objects.all()) selectors.py from django.db.models.query import QuerySet from books.models import Book def get_books() -> QuerySet[Book]: """ Return all objects of Book model. """ books = Book.objects.all() return books assertion error AssertionError: <QuerySet [<Book: test_book>]> != <QuerySet [<Book: test_book>]> -
Django - Slug is being applied to image file but is meant for object
class Project(models.Model): owner = models.ForeignKey(Profile, null = True, blank = True, on_delete = models.CASCADE) title = models.CharField(max_length = 200) description = models.TextField(null = True, blank = True) featured_image = models.ImageField(null = True, blank = True, upload_to = 'projects/', default = "projects/default.jpg") demo_link = models.CharField(max_length = 2000, null = True, blank = True) source_link = models.CharField(max_length = 2000, null = True, blank = True) demo = models.BooleanField(default = False, null = True, blank = True) tags = models.ManyToManyField('Tag', blank = True) vote_total = models.IntegerField(default = 0, null = True, blank = True) vote_ratio = models.IntegerField(default = 0, null = True, blank = True) created = models.DateTimeField(auto_now_add = True) slug = models.SlugField(default = '', editable = False, max_length = 200, null = False) id = models.UUIDField(default = uuid.uuid4, unique = True, primary_key = True, editable = False) def __str__(self): return self.title class Meta: ordering = ['-vote_ratio', '-vote_total', 'title'] unique_together = [['slug', 'owner']] @property def imageURL(self): try: url = self.featured_image.url except: url = '' return url @property def reviewers(self): queryset = self.review_set.all().values_list('owner__id', flat = True) return queryset @property def getVoteCount(self): reviews = self.review_set.all() upVotes = reviews.filter(value = 'up').count() totalVotes = reviews.count() ratio = (upVotes / totalVotes) * 100 self.vote_total = totalVotes self.vote_ratio = … -
How to style a ImageField in Django Froms using widget
click to see image Django Forms How to style the Imagefield using widget in Django forms -
pass data from models.py to views.py and show it to user
I want to give users ten point each time they fill out one Survey , so i have this code above and now how to add the 10 point to self user after he fill out one models.py : class User(AbstractUser): user_pic = models.ImageField(upload_to='img/',default="",null=True, blank=True) coins = models.IntegerField(default=10) def get_image(self): if self.user_pic and hasattr(self.user_pic, 'url'): return self.user_pic.url else: return '/path/to/default/image' def give_coins(user, count): user.coins = F('coins') + count user.save(update_fields=('coins',)) user.refresh_from_db(fields=('coins',)) class Survey(models.Model): name = models.CharField(max_length=200) published_on = models.DateTimeField('Published DateTime') def __str__(self): return self.name def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.published_on <= now was_published_recently.admin_order_field = 'published_on' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Participant(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) participation_datetime = models.DateTimeField('Participation DateTime') def __str__(self): return "Participant "+str(self.participation_datetime) class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) created_on = models.DateTimeField('Creation DateTime') def __str__(self): return self.question_text views.py : @register.inclusion_tag('survey/survey_details.html', takes_context=True) def survey_details(context, survey_id): survey = Survey.objects.get(id=survey_id) return {'survey': survey} @require_http_methods(["POST"]) def submit_survey(request): form_data = request.POST.copy() form_items = list(form_data.items()) print("form_items", form_items) form_items.pop(0) # the first element is the csrf token. Therefore omit it. survey = None for item in form_items: # Here in 'choice/3', '3' is '<choice_id>'. choice_str, choice_id = item choice_id = int(choice_id.split('/')[1]) choice = Choice.objects.get(id=choice_id) if survey … -
Django template - Javascript encodes URL wrong
This issue is really kinda starnge to me. At my Django application I want to send an S3 download link from my views.py to my template.html. If I do <p>{{ sprites_url }}</p> at my template, the url gets displayed correctly: https://localhost/test/sprites.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=2PsuWGctH4UQmGvEQYjTDsZ2HqGM%2F20220601%2Fminio%2Fs3%2Faws4_request&amp;X-Amz-Date=20220601T163847Z&amp;X-Amz-Expires=300&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Signature=6fbbac9f9a3f43e16b00857c67350054d3acdb3027ce66ada7664dced5d76114 As you can see, it contains &amp;. If I set the same sting at my template using Javascript <script type="text/javascript"> var signed_sprites_url = {{ sprites_url }}; </script> The string gets converted to this: https://test/sprites.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=2PsuWGctH4UQmGvEQYjTDsZ2HqGM%2F20220601%2Fminio%2Fs3%2Faws4_request&amp;X-Amz-Date=20220601T153759Z&amp;X-Amz-Expires=300&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Signature=cd575bd79883f1fec4e50cb14b2973bac7305f14517b7ca2a39f3f419b672b92 Why is &amp dropped out? -
how to get the last file uploaded to templates - DJAGO
i want to get the last file i was upload and it will be played in templates. but what i make it, every file i was upload, it can be played (so there’s so many audio player). what i want is just show 1 audio player with the last audio i was upload it. i was trying with this but it's not work on me. here's my html: {% for record in audio %} <audio controls="controls"> <source src="/media/mp3/{{record.audio}}" type="audio/mpeg"> </audio> {% endfor %} views.py: def homepage(request): form = AudioForm() audio = Audio_store.objects.all() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homepage") context={'form':form, 'audio':audio} print(audio) return render(request, "homepage.html", context=context) -
How to use nested serializers with Django rest mixins
I'm trying to implement CRUD operation in Django-REST framework with multiple models. The goal is to perform CRUD operation ron multiple table when the API call is made. I use mixins from REST framework https://www.django-rest-framework.org/api-guide/generic-views/#mixins I have found some relevant examples but still, my serializer is only returning the fields from the Student model for CRUDoperation. I'm not able to see the Course models field in REst api ui. PROBLEM I can't get the fields from Homework and Course models. How to display Data from two model without creating new model in Django? use of mixins class defined in Django rest framework models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" ###I combine both Student and Course into one class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks …