Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I keep getting an IntegrityError when i try to use Faker to populate my script
I've tried to delete the migrations folder and then redo the makemigrations process but i keep getting the same IntegrityError and it is probably coming from the migrations code itself but i don't understand it as the creation of the code was automatic by Django. The code below is my population script. import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "first_project.settings") import django django.setup() import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake-date)[0] if __name__ == '__main__': print('populating script') populate(20) print('populating complete') -
python argparse - pass file without using command line
I want to pass file using form-data to the argparse. But i'm not getting how to pass file to the argparse without using command-line. I also gone through the [https://stackoverflow.com/questions/31090479/python-argparse-pass-values-without-command-line] this solution but this is not helpful for me. I want to pass file using form-data. can anyone help? Thanks -
Enabling channels leads to SuspiciousFileOperation at /
I noticed that whenever I enable django channels in my code, I get the following error https://drive.google.com/file/d/1YDN8v7rFOsV6jXQseJBCsElXM0pFUC01/view settings.py: INSTALLED_APPS = [ "channels", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "debug_toolbar", "corsheaders", "rest_framework", "rest_framework.authtoken", "core", "drf_yasg2", ] WSGI_APPLICATION = "app.wsgi.application" ASGI_APPLICATION = "app.asgi.application" asgi.py: import os from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) }) Help would be much appreciated. Thank you in advance! -
how to send data in GET method from client side to server side - ajax
I'm trying to send two dates, start date and end date to return back between two dates , here is what i tried but doesnt work, $(document).ready(function(){ const date_inputs = new FormData(); $('#date_form').submit(function(e){ date_inputs.append('from',document.getElementById('from').value) date_inputs.append('to',document.getElementById('to').value) e.preventDefault(); }) console.log(date_inputs)//returns empty function dateTimePrices(){ $.ajax({ type:'GET', url:'/prices/dateTime/data', data:date_inputs, success:function(data){ const datetimes = data; 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 >search</button> </div> </form> i also tried this to create the dataForm, const date_inputs= (new Date(fromDate)).toUTCString(); but it say : Property 'append' does not exist on type 'string'.ts(2339) is there away to add date input into dataForm please and here is my django view code 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( … -
User registration with admin authorization
I was wonder if it is possible to include a way that when someone fill the user registration form to register, can the details be sent to an admin email for authorization before the user can login in django? -
Mapping roles in AzureAD to Django groups
Okay, I can now do SSO in Django via AzureAD by using django-microsoft-auth. But I would like to manage the groups there as well. For that we configured to pass roles in the token. But how do I map those to Django groups? I don't seem to find any example for that. -
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")