Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: UNIQUE constraint failed: items_auction.auction_id
I have a model called "Auction", it has a unique pk field called auction_id. Now i have a lot of data (over 50k records) and the problem is that when the database is not empty and im trying to upload another batch of records using bulk_create the error pops up. Here is my script for filling data auctions = [ Auction( auction_id=row[0], price=row[1], quantity=row[2], item_id=row[3], auctioned_item=Item.objects.get(item_id=row[3]) if Item.objects.filter(item_id=row[3]).exists() else None, realm_id = realm_id ) for row in reader ] items = [] for auction in auctions: if Auction.objects.filter(pk=auction.auction_id).exists(): Auction.objects.get(pk=auction.auction_id).delete() try: item = auction.auctioned_item if item not in items: item.last_auctioned_date = datetime.now() items.append(item) except: pass Auction.objects.bulk_create(objs=auctions, ignore_conflicts=True) Item.objects.bulk_update(items, ["last_auctioned_date"]) Here is the full error Traceback (most recent call last): File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: items_auction.auction_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\models\query.py", line 502, in bulk_create returned_columns = self._batched_insert( File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\models\query.py", line 1293, in _batched_insert self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts) File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\models\query.py", line 1270, in _insert return … -
which tools are more suitable for a web app that analyses data
I would like to build a hobby web app to learn more about data analysis. The idea is simple, I want to get publically available data via crawling, such as Covid data and then do some traditional data analysis and plot it on the web. I'm thinking, for the backend, pythong and nodejs seem both as a good choice. Now that I don't know any of them. I have done a lot of web development but never used python while I used nodejs a little bit. Since the app is a web app, nodejs seems a more suitable choice and it seems to have way more npm packages than pip. On the other hand, python seems more suitable for data analysis. What do you think is more suitable for the backend? Writing a web app with python seems like a lot of work while analyzing data with JS also seems like a lot of hustle. Is it practical to merge the two? Use nodejs for the backend and only use python to analysis the data brought by nodejs and then pass it back to nodejs to pass it to the frontend? -
Can't render form fields on profile page so that I can update profile image
Form code: class PFPform(ModelForm): class Meta: model = User fields = ['profile_pic' , 'username'] I added username to check/debug View code: def signed_in_view(request): form = PFPform() return render(request, "hobbies/signed_in.html", { "title": "Signed In Page", "h1": "Signed In Page", }) Where form is called on html template. <form method = "POST" action ="" enctype="multipart/form-data"> {%csrf_token%} {{ form }} <input class = "btn btn-primary" type = "submit"> </form> -
Django is looking for 'postgres' database
I have managed Postgresql database cluster on DigitalOcean. When I set the database parameters in the settings.py and run python manage.py migrate, I get the following error: FATAL: database "postgres" does not exist I've checked with pgAdmin and it is true that there's no postgres database, but why it should be there? My database username is doadmin and database name is defaultdb so why Django is trying to find postgres database? -
how can i add another section in django admin panel footer?
I am working on editing the default django admin panel. I want to add another field here. It already contains delete items. [it contains delete slected items][1] [1]: https://i.stack.imgur.com/Te5RL.png I cant find the correct file for the footer path of admin section. my delete_selected_confirmation.html looks like this. {% load i18n %} <div class="actions"> {% block actions %} {% block actions-form %} {% for field in action_form %}{% if field.label %}<label>{{ field.label }} {% endif %}{{ field }} {% if field.label %}</label>{% endif %}{% endfor %} {% endblock %} {% block actions-submit %} <button type="submit" class="button" title="{% translate "Run the selected action" %}" name="index" value="{{ action_index|default:0 }}">{% translate "Go" %}</button> {% endblock %} {% block actions-counter %} {% if actions_selection_counter %} <span class="action-counter" data-actions-icnt="{{ cl.result_list|length }}"> {{ selection_note }}</span> {% if cl.result_count != cl.result_list|length %} <span class="all hidden">{{ selection_note_all }}</span> <span class="question hidden"> <a href="#" title="{% translate "Click here to select the objects across all pages" %}"> {% blocktranslate with cl.result_count as total_count %}Select all {{ total_count }} {{ module_name }}{% endblocktranslate %}</a> </span> <span class="clear hidden"><a href="#">{% translate "Clear selection" %}</a> </span> {% endif %} {% endif %} {% endblock %} {% endblock %} </div> is this the right file … -
How to override the behaviour of allauth ConfirmEmailView to return a json instead of redirect URL?
I'm using allauth, for confirmation email view, and i need to return a JSON response to front end (React) after successful confirmation as React only understand the 200 but not 301/302, Please help me how i can solve it, Really exhausted. Thanks path('guest/registration/account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), -
Django forms taking pre-set value of submit button and not user input
I have two Django forms on one page, i seperate them like this: if request.method == "POST" and "bid" in request.POST: form1 = NewBidForm(request.POST) if form1.is_valid(): # Makes sure the big is higher than the previous highest bid if float(request.POST["bid"]) > listing.startingbid: # Saves bidding to database bidding = form1.cleaned_data["bid"] newbid = Bid(bid=bidding, user=request.user, listing=listing) newbid.save() listing.startingbid = bidding listing.save() return HttpResponseRedirect(reverse("listing", args=[name])) else: messages.error(request, 'This bid is not higher than the previous bid, try again!') return HttpResponseRedirect(reverse("listing", args=[name])) # If the form is not valid, return user to the original listing page else: return render(request, "auctions/listing.html", { "listing": listing, "comments": comments, "bids": bids, "highestbid": highestbid, "bidform": NewBidForm(), "commentform": NewCommentForm() }) # Handles user input for user placing a comment on a listing elif request.method == "POST" and "comment" in request.POST: form2 = NewCommentForm(request.POST) print(form2) if form2.is_valid(): # Saves comment to database comment = form2.cleaned_data["comment"] newcomment = Comment(comment=comment, user=request.user, listing=listing) newcomment.save() return HttpResponseRedirect(reverse("listing", args=[name])) else: return render(request, "auctions/listing.html", { "listing": listing, "comments": comments, "bids": bids, "highestbid": highestbid, "bidform": NewBidForm(), "commentform": NewCommentForm() }) The forms look like this: class NewBidForm(forms.Form): bid = forms.DecimalField(label="bid", decimal_places=2, max_digits=10) class NewCommentForm(forms.Form): comment = forms.CharField(label="comment", widget=forms.Textarea) and my HTML looks like this: <form action="{% url 'listing' … -
Django ViewSet with async external calls
I have a Django viewset with actions (endpoints). I have to call two services and - since their response times are long - I want to make it asynchronously. For some reason this code executes synchronously (get_bad_things starts only after get_good_things finishes). import asyncio import requests from rest_framework import viewsets from rest_framework.response import Response class AllThingsViewSet(viewsets.ViewSet): @action(detail=False, url_path="get_things/") def get_things(self, request) -> Response: async def get_good_things(cls): return requests.get("https://stackoverflow.com/") async def get_bad_things(cls): return requests.get("https://stackexchange.com/") try: loop = asyncio.get_event_loop() except RuntimeError: asyncio.set_event_loop(asyncio.new_event_loop()) loop = asyncio.get_event_loop() things = loop.run_until_complete( asyncio.gather(*[get_good_things(self), get_bad_things(self)]) ) return Response(things[0], status=200) What am I doing wrong? I use gunicorn WSGI. -
Django: how to test type of RelatedManager?
How to test the type of a RelatedManager in Django ? assert type(qs) in [models.QuerySet, models.Manager] fails if qs is a RelatedManager how do I test if qs is a RelatedManager ? -
django LoginView redirecting to accounts/profile instead of success_url
I have two user types usertype a and user type b i am trying to create a two seperate login forms and views using AuthenticationForm and Loginview i am getting redirected to accounts/profile after logging in forms.py class myForm(AuthenticationForm): def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: user = authenticate(self.request, username=username, password=password) if user is None: raise self.get_invalid_login_error() else: if user is not None: if user.usertype_a: login(self.request,user) return self.cleaned_data views.py class MyLoginView(LoginView): template_name = 'log.html' form_class = myForm success_url = reverse_lazy("home") -
How to use redis-sentinel?
Can Anyone please explain the working of this redis sentinel with master-slave configuration as explained in the image below. -
Error installing a django project AttrributeError: module 'collections' has no attribute 'Iterator'
i am trying to use this project https://github.com/tangjon/Build-a-PC-Configuration-Tool but i have an error in the process. First of all i am cloning the project using this command: git clone https://github.com/tangjon/Build-a-PC-Configuration-Tool.git after that i am changing directory and go to: cd Build-a-PC-Configuration-Tool installing the requirements: pip install -r requirements.txt change directory again to go into the manage.py for migrations: cd bapccanada then migrate: python manage.py make migrations and here is the error AttributeError: module 'collections' has no attribute 'Iterator' enter image description here Any ideas to solve the error? Thank you in advance! -
Django: How to trigger a function whenever certain objects are modified from the wagtail interface
I have a long list of "Quotation" objects. The price of a quotation depends on dozens of children (and grand children) objects. The lowest one being the rate/hour. When I change the children objects of a quotation like the rate/hour, the quotation price changes. I would like to recalculate the price of each quotation that is impacted by any change I make on their consistuant objects automatically. I am using Wagtail for the object admin. I am not sure about the way to do that, should I use signals? Wagtail hooks? -
how to put data from a form submition (get method) into a dictionary - ajax
I'm trying to send some data to backend the data is from date type inputs here is my template $(document).ready(function(){ const datainputs = new FormData(); $('#date_form').submit(function(e){ datainputs.append('from',document.getElementById('from').value) datainputs.append('to',document.getElementById('to').value) e.preventDefault(); }) console.log(datainputs)//returns empty function dateTimePrices(){ $.ajax({ type:'GET', url:'/prices/dateTime/data', data:datainputs, success:function(data){ const datetimes = data; console.log(datetimes) spinner.setAttribute('hidden',true); var k = '<tbody>'; if(datetimes){ k+= '<tr>'; k+= '<td>' + datetimes["all_qnt"] + '</td>'; k+= '<td>' + datetimes['all_price'] + '</td>'; k+= '</tr>' }else{ k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=2>not found</td>' } k+='</tbody>' document.getElementById('datetime_prices_list').innerHTML = k } }) } dateTimePrices(); }) <form action="" method="GET" id="date_form"> <div class="col-11 p-1 mt-1 mx-auto text-center row rtl "> <p class="col-12 col-sm-6 mx-auto text-left row"> from <input type="date" class="form-control col-9 mr-1" name="from" id="from"> </p> <p class="col-12 col-sm-6 mx-auto text-right row"> to <input type="date" name="to" class="form-control col-9 mr-1" id="to"> </p> <button type="submit" class="btn btn-info col-8 col-sm-5 col-md-3 mx-auto">search</button> </div> </form> in the console returns empty values in formData ! i've to send the two date to backend if the two date exists if not, it will return the entire data and here is my backend - django def priceByDateTime(request): start = request.GET.get('from') end = request.GET.get('to') print(start,end)# if start and end: datetimes = MyModel.objects.filter(invoice__created_at__range=(start,end)).annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') … -
how to filter multiple messages in django
so i recently did a filter for messages so as to bring all the messages between two people def pmessage(request, pk): user = User.objects.get(id=pk) message = pm.objects.filter(Q(receiver=request.user, sender=user) | Q(receiver=user, sender=request.user)) form = dmform() context = { 'message' : message, 'form' : form, } it works, only that it groups the messages in categories ie, it would list all the messages that meets one criteria before the other irrespective of which message came first, and that defeats my aim. thanks you -
on using instence= (class name) <django.db.models.query_utils.DeferredAttribute object at 0x00000256CA7C05E0>
views.py geting path in output instide of values present in it I am trying but not gating answers please provide me some suggestions from django.shortcuts import render from django.http import * from MYapp.models import * from .form import * def venue(request): venue_list = Task.objects.all() return render(request,'MYapp/venue.html',{'venue_list': venue_list}) def navebar(request): return render(request,'MYapp/navebar.html') def db(request,db_id): venues = Task.objects.get(pk=db_id) return render(request,'MYapp/db.html',{'venues': venues}) def search(request): if request.method =="POST": searched = request.POST.get('searched', False) Tasks =Task.objects.filter( firstname__contains = searched) return render(request,'MYapp/search.html',{'searched':searched, 'Tasks':Tasks}) else: return render(request,'MYapp/search.html',{}) def update(request,db_id): venues = Task.objects.get(pk=db_id) form = TaskForm(request.POST or None, instance=Task) return render(request,'MYapp/update.html',{'venues': venues,'form':form}) -
Django - Deleting using modal: show and delete only the first item from the table
Please help me understand the problem. I try to use the modal to delete each line separately but instead of displaying and deleting my actual line, it always displays and deletes the first line in the table. Where am I wrong with the code? Below my settings. Thank you very much. models.py class Post(models.Model): class DisplayOnlyPublicat(models.Manager): def get_queryset(self): return super().get_queryset() .filter(status='publicat') options =( ('draft', 'nepublicat'), ('publicat', 'publicat') ) title = models.CharField(max_length=250) poster = models.ImageField ( upload_to ='posts/', default='posts/poster_articole_pp.jpg') category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1) slug = models.SlugField(max_length=250, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) author = models.ForeignKey (User, null=True, on_delete=models.SET_NULL, related_name='profipedia_posts') short_content = models.TextField(null=True) # content = models.TextField() # content = RichTextField() content = RichTextUploadingField(external_plugin_resources=[( 'emojione', '/static/vendor/ckeditor_plugins/emojione/' , 'plugin.js', )],) status = models.CharField(max_length=10, choices=options, default='draft') id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) objects = models.Manager() #denumire initiala dop = DisplayOnlyPublicat() # denumire custom def get_absolute_url(self): return reverse('posts:articol', args=[self.slug]) # sa deschida articolul pe baza de denumire(slug) din sectiunea admin indiferent de statusul articolului (publicat/nepublicat) # def get_absolute_url_adm(self): # return reverse('posts:articolAdm', args=[self.slug]) class Meta: ordering = ('-publish',) def __str__(self): return self.title views.py def delete_articol(request, articol_id): post = Post.objects.get(pk=articol_id) post.delete() messages.success(request, "Articolul a fost sters!") return redirect('posts:articoleAdm') urls.py urlpatterns = [ path('', views.articole, name='articole'), path('articole-admin/', views.articoleAdm, name='articoleAdm'), … -
Specify the pages that navbar items should appear on with Bootstrap in Django
I am trying to specify the page that this navbar dropdown should appear on. I tried adding this line: {% if request.resolver_match.url_name == 'club_selection' %} class = "active" {% endif %} but that doesn't seem to do anything for me. Maybe I am using it wrong. If anybody knows how to do this correctly it would be a massive help. club_selection_dropdown.html <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item dropdown"> <li {% if request.resolver_match.url_name == 'club_selection' %} class = "active" {% endif %}> <a class="nav-link" href="/" id="club--dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Current Clubs <span class="bi-arrow-down-circle-fill"></span> </a> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="club-dropdown"> {% for club in clubs %} <form action = "{% url 'group_check' user.id %}" method = "post"> {% csrf_token %} <input type="hidden" name="club_name" value="{{ club.club_name }}"> <style> .btn:hover { background-color: lightgrey; } .btn-group.special { display: flex; } .special .btn { flex: 1; } </style> <div class="btn-group special" role="group"> <input type = "submit" value = "{{club.club_name}}" class="btn col-xs-11 text-left" style=".btn-primary:hover; text-align:left; padding-left:6px"> </div> </form> {% endfor %} </ul> </li> </li> </ul> </div> views.py def club_selection(request): list_of_clubs = ClubList() clubs = list_of_clubs.club_list return render(request, 'club_selection.html', {'clubs':clubs}) -
Appointment booking system. Avoid double bookings
I am currently trying to build an appointment system. This works fine however the function doesn't catch if the same appointment has already been booked in the models. class BookingView(FormView): form_class = AvailabilityForm template_name = "availability.html" def form_valid(self, form): data = form.cleaned_data bookingList = Appointment.objects.filter() for booking in bookingList: if booking.start > data["end_time"] or booking.end < data["start_time"]: booking=Appointment.objects.create( name=data["name"], start=data["start_time"], end=data["end_time"] ) booking.save() print(booking.start) print(data["start_time"]) return HttpResponse("can be booked") else: print(booking.start ) print(data["start_time"]) return HttpResponse("Cant be booked") -
How to test GET and POST api which requires user logged in pytest Django?
I have created a fixture to create user in conftest.py @pytest.fixture def test_password(): return 'strong-test-pass' @pytest.fixture(scope='session') def create_user(db, test_password): def make_user(**kwargs): employee = e_ge_employee.objects.create() kwargs['password'] = test_password if 'username' not in kwargs: kwargs['username'] = str(uuid.uuid4()) if 'employee' not in kwargs: kwargs['employee'] = employee return e_ge_user.objects.create(**kwargs) return make_user and then wrote a testcase to check login in test_urls.py @pytest.mark.django_db def test_auth_view(client, create_user, test_password): user = create_user() url = '/accounts/login/' client.login( username=user.username, password=test_password ) response = client.get(url) print("RESPONSE - ",response) assert response.status_code == 200 Now I want to write a test case to test GET and POST API and the APIs will only work if the user is authenticated, Can someone please provide me with the solution.....Thanks in Advance -
Render html content stay on current page with form action set to different url in Django
My question is there is a way to render html content(bootstrap alert) on the current page(1st page) with POST action set to a different url(2nd page)? I have following content in views.py: def calendar(req): # 1st page return render(req,'calendar.html') def result(req): # 2nd page if req.method == 'POST': xxx else: no_data = "xxx" context = { 'no_data': no_data } return render(req, 'calendar.html', context) xxx return render(req,'result.html',context) The form info is submitted to different url(2nd page) in calendar.html: {% if no_data %} <div class="alert alert-warning" role="alert"> {{ no_data }} </div> <form action="{% url 'result' %}" method="POST"> Thank you. -
How to migrate remote postgres db into my local django project?
I am creating a Django project where I have to use existing database data. The existing database is Postgres and it is hosted on Aws. My goal is to copy them from Aws to my local Postgres DB and use in my project. Thanks -
Django using Amazon S3
So whenever I run the following a staticfiles folder gets created and I can't collectstatic to my AWS S3 bucket. (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> python manage.py collectstatic Found another file with the destination path 'user\main.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', 'storages', ] STATIC_ROOT = 'static/' # All of this is in my console.aws.amazon to configure aws s3 static files only # IAM Management Console AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', '') # Amazon S3 Buckets AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', '') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Typescript endpoint to list users in Django
So I have a Django project and I want to create a typescript endpoint to list which users live in a certain postal code. I have never used typescript so I don't know how to create it and integrate it with the django project. Help is much appreciated. the models.py if it is useful: class UsuarioMaster(models.Model): nombre = models.CharField(max_length=50) class UsuarioDetalle(models.Model): usuario = models.ForeignKey(UsuarioMaster, on_delete=models.CASCADE, null=True) codigo_postal = models.CharField(max_length=5) ciudad = models.CharField(max_length=50) pais = models.CharField(max_length=50, default='') -
How do I create a QR code in Python without saving it as an image
I am trying to make Qr Codes using Python on a Django applicaiton using this code : def generate_qr_code (reference): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4, ) qr.add_data(reference) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white").convert('RGB') filename = reference+".jpeg" img.save("C:\\qrs\\"+filename) Now, this function is called when I click on a "Generate Qr Code" Button. My problem is that I would like the Qr Code to be displayed on a new tab on my browser instead of it being saved as an image, as I only need to print them on paper at that moment and I have no need to keep the images. Thank you for your help.