Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm trying to add comment posting on my Django website
I was trying to create a form with django, but it raises NoReverseMatch error. Django version 3.1.5. Views: try: a = Article.objects.get(id =article_id) except: raise Http404("Article not found") a.comment_set.create(author_name= request.POST['name'], comment_text =request.POST["text"]) return HttpResponseRedirect(reverse("aricles:detail", args = (a.id,))) Urls: app_name = "articles" urlpatterns = [ path("", views.index, name="index"), path("<int:article_id>", views.detail, name="detail"), path("<int:article_id>/leave_comment", views.leave_comment, name="leave_comment"), ] Html: <form action="{% url 'articles:leave_comment' article.id%}" method="POST"> {% csrf_token %} <input type="text" required placeholder="Your name" name = "name"><br> <textarea name="text" required="" placeholder="Comment" cols="30" rows="10"></textarea><br> <button type="submit">Post a comment</button> </form> Thanks for your help! -
Django queryset top 3 of sum for each year
I need to find the top 3 customers per year from the sum of their related invoices. So, I got 2 models Customer related to Invoice by a FK. I get the total sales foreach as following: qs = Company.objects\ .filter(invoices__status=Invoice.PAID)\ .annotate(year=TruncYear('invoices__created')).values('year', 'name')\ .annotate(total=Sum('invoices__total'))\ .exclude(total=None)\ .order_by('year', 'total') But what if I'd like to get only the top 3 per year? Should I iterate manually: years = [year.year for year in set(qs.values_list('year', flat=True))] for y in years: new_qs = qs.filter(year__year=y).order_by('-total')[:3] my_top.append(new_qs) Isn't it a way to get the limited queryset in one shot? -
How to set value of model field as currently logged user? Django
I have Event model which has a field creator as ForeignKey with attribute User. In views.py I have create_event which creates event using EventForm. How to set default value of creator in EventForm as currently logged user? It is set default as admin, I do not want to set it manually every time I create an event, because it would me annoying if I have a lot of users created. modely.py class Event(models.Model): SPORT = ( ('Football', 'Football'), ('Volleyball', 'Volleyball'), ('Basketball', 'Basketball'), ('Futsal', 'Futsal'), ('Tennis', 'Tennis'), ('Handball', 'Handball'), ('Ice Hockey', 'Ice Hockey'), ('Paintball', 'Paintball') ) creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) sport = models.CharField(max_length=20, null=True, choices=SPORT) event_name = models.CharField(max_length=30) event_date = models.DateTimeField(default=date.today()) end_event_date = models.DateTimeField(default=date.today()) current_members = models.IntegerField(default=1) total_members = models.IntegerField(default=0) event_location = models.CharField(max_length=50) cost = models.FloatField(default=0, max_length=5) description = models.CharField(max_length=300, blank=True) def __str__(self): return self.event_name views.py @login_required(login_url='login') def create_event(request): form = EventForm() if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'events/create_event.html', context) forms.py class EventForm(ModelForm): class Meta: model = Event fields = ['creator', 'sport', 'event_name', 'event_date', 'end_event_date', 'total_members', 'current_members', 'event_location', 'cost', 'description'] -
Django User.objects.filter() with list of strings?
I am trying to filter QuerySet from a list of strings using __in lookup, I am not sure how I can get all users with first_name in the list. names = ['Bob', 'Tina', 'Ankit'] User.objects.filter(first_name__in=names) What it's returning is, First correct match ignoring other items in list. This lookup works fine with list of integers ie. ids = [1, 2, 3] User.objects.filter(id__in=ids) May be I've to use some other lookup, but I am not sure which one. Thanks -
Fieldset values displaying in profile page but if another person registered it showing error in profile page -django
I have member table for registered persons.. I want to display that member table values of particular person in profile page who is logged in... i used Member.objects.get() data is displaying in the profile page of the person who is logged in. but if another person registered it showing error in profile page like.. this is my error MultipleObjectsReturned at /web/profile/ get() returned more than one Member -- it returned 2! this is my views.py code def profile(request): member = Member.objects.get() print(member.Email) return render(request, 'web/profile.html',{'member':member} ) -
Flutter Razorpay Payment gateway integration from Django rest Framework
I am using razorpay payment integration for my project. I am stucked in one prblm. The problem is that when I am pressing the Success button after payment peoceed, I want to Store the data into db like payment_id, order_id, payment_signature from an API call. The API is written in django. How can I store thise data to the db? Is it depends on the API? Or I can directly do this from flutter sdk integration itself?? Can anyone have any Idea regarding this? -
How to connect pinax.points and pinax.badges with oscar.customer user model?
How to connect pinax.points and pinax.badges with oscar.customer user model ? After forking customer app from oscar -> , e.g: I declared this model : class UserBadge(models.Model): user = models.ForeignKey( AUTH_USER_MODEL, related_name="badges_earned", on_delete=models.CASCADE, null=True, verbose_name=_("User")) I want to add new tow new fields : points from pinax.points, badge from pinax.badges. -
When I try to logout showing Page not found (404)
Whenever I click log out this error is showing My html is: views.py : apps urls.py : procjects urls.py : -
Django SUM Query with VIEW Statement
I am trying to sum query whole table using Django Query. I have an also Postgresql database working with my django. My Table workoutsummaryview: (actually its VIEW statements): user_id workout results 1 Bench 281.31 1 Flat 137.06 1 Bench 1497.91 1 Bench 64.50 1 SQ 555.65 1 Wrench 2803.39 1 Flat 2115.73 1 Bench 10578.63 1 Flat 146.52 1 Flat 1770.65 1 Wrench 22.61 My views.py def workoutsummary (request): dailyworkout = Dailyw.objects.filter(user_id=request.user.id) workout = Workout.objects.filter(user=request.user, datecompleted__isnull=True) dailyr = Dailyw.objects.aggregate(Sum('results')).values() My models.py class Daily(models.Model): user_id = models.CharField(max_length=100) title = models.CharField(max_length=100) results = models.BigIntegerField(max_digits=5, decimal_places=2) class Meta: managed = False db_table = "workoutsummaryview" According the django aggregation reference page I did try on template like : {{ results }} and {{ dailyr.results__sum }} But nothing happens. I also tried with if and for tag, but that didn't work either. I think so i missed something important. I really appreciate if someone could help me out. Thank you in advance. -
Why is setting initial field values not working in django admin?
I have some code that doesn't do what I would expect even after thorough debugging. I have class AgregatororderAdmin(admin.ModelAdmin): ... on which I call def change_view(self, request, object_id, form_url='', extra_context = None): if self.form.base_fields["ProcessingPersonAdminId"].initial == None: self.form.base_fields["ProcessingPersonAdminId"].initial = request.user.id self.form.base_fields["ProcessingPersonName"].initial = request.user.username ... return super().change_view(request, object_id, form_url, extra_context=extra_context, ) when I check, the initial values, it is set correctly. But in the admin change view it does not display. I would appreciate any hint on why the changes are not applied. -
NoReverseMatch at / UpdateView
I try to use an updateview with a form. I get the error: Reverse for 'response' with arguments '('',)' not found. 1 pattern(s) tried: ['tower/rsp/(?P[-a-zA-Z0-9_]+)/$'] views.py: class ResponseView(UpdateView): model = Model fields = ['response'] urls.py path( route='response/<slug:pk>/', view=views.ResponseUpdateView.as_view(), name='response' ) template: <form method="post" action="{% url 'app:response' pk %}"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Send</button> </form> the error is in the template {% url 'app:response' pk %} specifically pk, I have tried using: def get_context_data(self, **kwargs): context = super(ResponseUpdateView, self).get_context_data(**kwargs) context['slug'] = self.kwargs['pk'] together with {% url 'app:response' slug %} If I don't add the url everything works fine -
ajax preventDefault() is not working with django form
I have a problem with ajax form submission. My problem is whenever I click submi it redirect me to a new page and show me the responses there. here is my django view @csrf_exempt def my_view(request): if request.is_ajax and request.method == "POST": # do something and if successfully return JsonResponse({'success': True}, status=200) # if not success return JsonResponse({'fail': True}, status=400) # other thingss my template <div id="form-div"> <form action="{% url 'my_view' %}" method="POST" id="my-form"> # some fields .. <button type="submit">submit</button> </form> </div> ajax $("#my-form").submit(function (e) { e.preventDefault(); $.ajax({ type: "POST", url: my_url, data: {some datas}, success: function (response) { # some jquery code to update DOM }, error: function (response) { # some jquery code to update DOM } }) }) Now the code above that i showed you works fine for me but the problem comes if I append the form on event like this. <button id="my-btn">my btn</button> $("#my-btn).click(function(e) { e.preventDefault(); $(#form-div).append( " <form action="{% url 'my_view' %}" method="POST" id="my-form"> # some fields .. <button type="submit">submit</button> </form> " ); }) after I clicked the button and inspected the form it showed the exact same as my original form but if i do the post request it will redirect me … -
Django. M2M field with throug model vs. manual intermediate model?
What are the advantages of using many to many field with through model versus manually creating the intermediate model? Let me use the example in the documentation: from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) The tables created in Postgresql, in my case, and the admin page in Django would be the same as the ones created with: from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) ## members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) The main advantage I found is that it is possible to create a inline form set at the admin page and the serializers may be easier; but a part from that, as I see, technically both options are the same. -
Cant handle model IntegrityError in django
I have model that contains name field with unique = True like below class MyModel(models.Model): name = models.CharField(max_length=100 , unique= True) When I try to submit duplicate data in my model it raise IntegrityError as expected but I can't handleit in except block in my view. from django.db import IntegrityError try : name = MyModel(name= my_new_name) except IntegrityError: return HttpResponse('Error') # this code never execute My error: django.db.utils.IntegrityError: UNIQUE constraint failed -
django.db.utils.IntegrityError: null value in column "author_id" of relation "movie_movie" violates not-null constraint no idea why is this occurring
Seems like model is only getting "null". I tried to print the request user in views and it was fine. View codes. def add_item(request): # add new media quote = random.choice(quotes) if request.method == "POST": new_item = MovieForm(request.POST) new_item.save(commit=False) new_item.author = request.user new_item.save() return redirect('movie:movie_library') else: movie_form = MovieForm() return render(request, 'movie/add_movie.html', context={'form': movie_form, 'quote': quote}) model class Movie(models.Model): STATUS_CHOICES = ( ('Movie', 'Movie'), ('Tv-series', 'Tv Series'), ('Anime', 'Anime'), ) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=False) type = models.CharField(max_length=15, choices=STATUS_CHOICES, default='') year = models.IntegerField(null=True, blank=True) rating = models.FloatField(max_length=10, null=False) review = models.TextField(null=True, blank=True) img_url = models.TextField(default='https://betravingknows.com/wp-content/uploads/2017/' '06/video-movie-placeholder-image-grey.png') active = models.BooleanField(default=True) def __str__(self): return self.title error django.db.utils.IntegrityError: null value in column "author_id" of relation "movie_movie" violates not-null constraint DETAIL: Failing row contains (46, Sapiens, Movie, 435, 6.5, ftght, https://betravingknows.com/wp-content/uploads/2017/06/video-movi..., t, null). -
How to plot a horizontal bar chart for one data item in python version of chartJS (pychart.JS)
Hi I am trying to plot a horizontal bar chart using pychart.js library (https://github.com/IridiumIO/pyChart.js). <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script> <div class="grid-container"> <div class="grid-item"> <canvas id="myChart1" width="400" height="100" style="border: 2px solid black; padding: 30px 50px; margin-bottom: 20px;"></canvas> </div> </div> <script> var data = {{ chartJSON | safe }} var ctx = document.getElementById("myChart1").getContext('2d'); var myChart = new Chart(ctx, data); </script> the python code was like as following: from pychartjs import BaseChart, ChartType, Color class MyBarGraph(BaseChart): type = ChartType.HorizontalBar class data: class numerics: label = "Dimension I1" value = 25 data = [value] backgroundColor = Color.RGBA(190, 159, 87) xAxisID = 'numerics' class compensate: max_val = 100 value = 25 label = "Total" data = [max_val-value] backgroundColor = Color.Gray xAxisID = 'compensate' class options: responsive = False maintainAspectRatio = False legend = Options.Legend(display=True) scales = { "xAxes": [{ "id": "numerics", "display": False, "stacked": True, "ticks": { "suggestedMin": 0, "suggestedMax": 100 } }, { "id": "compensate", "display": False, "stacked": True, "ticks": { "suggestedMin": 0, "suggestedMax": 100 } }], "yAxes": [{ "display": False, "stacked": True }], } In django view the following code was written, def homepage(request): NewChart = MyBarGraph() NewChart.data.label = "My Favourite Numbers" # can change data after creation ChartJSON = NewChart.get() return render(request=request, template_name='home.html', context={"chartJSON": ChartJSON}) … -
Django Swagger starts failing when include is used in django urls
I am using django rest_framework_swagger for my django project, everything was working fine but when I added some URLs with include method Swagger start giving me 500 internal server error. I am not sure why this error is coming, I have checked but didn't find anything to fix this error. I am using: django 1.11.7 rest_framework_swagger 2.1.2 django rest framework 3.7.3 URLs from django.conf.urls import url, include from link_one.views import LinkOneViewSet from link_two.views import LinkTwoViewSet schema_view = get_swagger_view(title='My Project APIs') urlpatterns = [ url(r'^$', schema_view), url(r'^foo/(?P<foo_id>\w+)/bar/(?P<bar_id>\w+)/link1', LinkOneViewSet.as_view({'get': 'list'})), url(r'^foo/(?P<foo_id>\w+)/bar/(?P<bar_id>\w+)/link2', LinkTwoViewSet.as_view({'get': 'list'})), url(r'^foo/(?P<foo_id>\w+)/bar/(?P<bar_id>\w+)/link3', include('link_three.urls')) ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Error [25/Jan/2021 14:03:31] ERROR [django.request.exception:135] Internal Server Error: / Traceback (most recent call last): File "C:\Users\myuser\conda_env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\myuser\conda_env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\myuser\conda_env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\myuser\conda_env\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\myuser\conda_env\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\myuser\conda_env\lib\site-packages\rest_framework\views.py", line 489, in dispatch response = self.handle_exception(exc) File "C:\Users\myuser\conda_env\lib\site-packages\rest_framework\views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\myuser\conda_env\lib\site-packages\rest_framework\views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\myuser\conda_env\lib\site-packages\rest_framework_swagger\views.py", line 32, in get schema = generator.get_schema(request=request) File "C:\Users\myuser\conda_env\lib\site-packages\rest_framework\schemas\generators.py", line 278, in … -
update tree structure in django models
I have this tree of nodes, which I should store them in sqlite database. I'm using this tree like a cache so I have to be able to read fast, but also I'm going to update it periodically. I have seen django-treebeard which has some easy to use functions, but I'm still not sure about the update part. Is there any better library for this case? or what is the best implementation of update which I can add to django-treebeard functionalities? -
Uploaded django project not running on AWS
I uploaded django project few days ago. When I uploaded it was running fine but when I tried to reconnect using .pem file I am getting: Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. I dont know what is issue. Can someone help me why it is happening? In terminal it is showing runnning: (env) ubuntu@ip-172-31-31-227:~/AWS-test/mysite$ gunicorn --bind 0.0.0.0:8000 mysite.wsgi:application [2021-01-25 08:16:00 +0000] [41503] [INFO] Starting gunicorn 20.0.4 [2021-01-25 08:16:00 +0000] [41503] [INFO] Listening at: http://0.0.0.0:8000 (41503) [2021-01-25 08:16:00 +0000] [41503] [INFO] Using worker: sync [2021-01-25 08:16:00 +0000] [41505] [INFO] Booting worker with pid: 41505 -
Pass Variable to Matplotlib in Django Template
I'm using this code to create a plot on my site views.py def setPlt(): x = ["07/01", "07/02", "07/03", "07/04", "07/05", "07/06", "07/07"] y = [3, 5, 0, 5, 6, 10, 2] plt.bar(x, y, color='#00d5ff') plt.title(r"$\bf{Repli Graph}$", color='#3407ba') plt.xlabel("Date") plt.ylabel("Number of Repli") def plt2svg(): buf = io.BytesIO() plt.savefig(buf, format='svg', bbox_inches='tight') s = buf.getvalue() buf.close() return s def repli_plot(request): setPlt() svg = plt2svg() plt.cla() response = HttpResponse(svg, content_type='image/svg+xml') return response urls.py path("", views.RecordDay.as_view(), name="media_power-add_record") in html <img src="{% url 'media_power-plot' %}" width=800 height=400> I have some dummy values to create a graph. But I would like to know how could I pass variables with values from TemplateView I'm using on the page where I'm generating graph. I'm passing values to jinja in context like this return render(request, self.template_name, self.context) I want self.context values in my plot -
Is there a way to change id of data frames appended in Pandas?
so I have two data frames, and used .append() method to merge them vertically. However, I get an error of which I assume the cause is duplicate id's. Here is a sample of the data frames. A B 1 a1 b1 2 a2 b2 3 a3 b3 4 a4 b4 A B 1 q1 w1 2 q2 w2 3 q3 w3 4 q4 w4 Now the merged data frame looks like this: A B 1 a1 b1 2 a2 b2 3 a3 b3 4 a4 b4 1 q1 w1 2 q2 w2 3 q3 w3 4 q4 w4 Now, I'd like to change the id of each row. Would that be possible? Thanks. -
django admin static files are uploaded to s3 via `collectstatic` but not served when running locally
I'm following this tutorial for storing static and media files on s3. This is what my static files configuration in settings.py looks like: USE_S3 = os.getenv('USE_S3') == 'TRUE' ## AWS Configuration if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None # differs from the tutorial because the bucket is private AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles' After setting all the env variables I run python manage.py collectstatic and I can see that the files have been successfully uploaded to my s3 bucket. I.e. I see static/admin/ directory on s3 with fonts, css, etc. However when I run the server locally the admin panel is missing all the css. I'm not sure why django cannot find the admin static files given that collectstatic worked. I found several other tutorials here, here and here but I can't find what I'm missing. For all of them it seems like it's supposed to "just work" after running collectstatic... What did I forget? -
Passing ID to Django URL
Good day Stack Overflow; I want to use a url to access data from database base on the data's ID. I know there are duplicates of the same question here on SO but I cant seem to figure out something so basic. Hope you can help me with this. Everything works out except on my template. if I pass the url as: <a href="{% url 'job_details' 5 %}"> It will get the Job with ID of 5. But if I use <a href="{% url 'job_details' PropositionItem.id %}"> It will return Reverse for 'job_details' with arguments '('',)' not found. 1 pattern(s) tried: ['jobs/details/(?P<id>[0-9]+)$'] as Error Message. My Model is something like this: class PropositionItem(models.Model): created = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey('users.Account', on_delete=models.CASCADE) job_title = models.CharField(max_length=100, default='', null=False) views.py path('details/<int:id>', views.job_details, name='job_details'), What should I write on my href? -
How to create choice field in django model using another model
I have two models first User model and second Organization Model. Admin will be responsible for adding data in Organization Model.So I have used Foreign key. class Organizaton(models.Model): name = models.CharField(max_length=255) status = models.BooleanField(default=True) created_by = models.ForeignKey(CustomUser,on_delete=models.CASCADE,limit_choices_to= {'is_staff': True}) created_date = models.DateTimeField(auto_now_add=True) and I have a Custom User table where I want to store which user belongs to which Organization: class CustomUser(AbstractUser): organization_name = models.ForeignKey(Organization,on_delete = models.CASCADE) So,here what issue i am facing is If I declare CustomUser Class First then there is an error inside CustomUser class in organization_name field that says class Organization is not Found or declared and if i declare Organization Model class before CustomUser model class then i am getting error inside Organization class in created_by field saying CustomUser class not found or declared. How can I solve this issue. Thanks in Advance. -
Gmail's image broken links when sending mails through Django
I'm sending an email using the SMTP protocol in Django. When I send the image link it is like this: https://example.com/images/pic1.jpg But Gmail converts it to something like this: https://ci5.googleusercontent.com/proxy/vI79kajdUGm6Wk-fjyicDLjZbCB1w9NfkoZ-zQFOB2OpJ1ILmSvfvHmE56r72us5mIuIXCFiO3V8rgkZOjfhghTH0R07BbcQy5g=s0-d-e1-ft#https://example.com/images/pic1.jpg I tried the image URL proxy whitelist setting. It is showing the preview of the image.But image links are not working. PS: I have also tried methods suggested here but to no avail.