Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker Django 1.7 django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates:foo?
I know this question is similar to many prior cases, for example: [1]: How to resolve "django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: foo" in Django 1.7? , but my issue was happened while I was running my Docker images. The Django application compiled successfully while I was on locally, but after I built my docker image and tried to run it. It shows " Application labels aren't unique: foo". I guess it might related to "Cache". I thought on local, there might be a cache, but no cache in docker image, so the compiler doesn't recognize the name of the label? That's the issue came from? -
Is it a bad practice to write an interactive step on a unit test?
From what I understand the main purpose of unit testing is to automatize testing. But consider the following example: I have an application that needs the user to read a QR code. When the user reads the QR code, the user is connected to another application. My application then checks if the user is connected. So, the only way that I think to test this scenario, is to when running the test case, display a QR code in the console so that the developer read it. But I think it's a bad practice. So my question is: "Is it a bad practice to write an interactive step on a unit test ?" Can anybody give me another way to test this scenario? Maybe there is some kind of tool that I dont know? I'm using django in this application. Thank you. -
How to properly join two Django query sets
I have the following logic implemented in an endpoint. def get(self, request, branchName, stack, resultType, buildNumberMIN, buildNumberMAX, format=None): try: # use ONE query to pull all data relevant_notes = Notes.objects.filter( branchName=branchName, stack=stack, resultType=resultType) # filter on the endpoint parameters (range of numbers) requested_range = relevant_notes.filter( buildNumber__gte=buildNumberMIN, buildNumber__lte=buildNumberMAX) # also pull latest note -- regardless of requested range latest_note = relevant_notes.latest('buildNumber') # join the notes return_set = requested_range | latest_note #serialize the data serializer = serializers.NoteSerializerWithJiraData( return_set, many=True) return Response(serializer.data) except Notes.DoesNotExist: return Response({"message": f"No notes found"}, status=404) Context: the logic is put simply, fetch a range of notes, but also include the latest note based on the url parameters. If the range of notes contains no data, still return latest. The issue I am facing is AttributeError at /api/v2/notes/Test/Test/Test/1/2/ 'Notes' object has no attribute '_known_related_objects' It is possible that it does not like that I add attempting to combine a query set with a single object... -
Accessing an object based on foreign key link in Django template
I currently have some models linked using foreign keys (reduced) models.py: class Saga(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=1000) startChapter = models.PositiveIntegerField() endChapter = models.PositiveIntegerField() class Arc(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=1000) saga = models.ForeignKey(Saga,on_delete=models.SET_DEFAULT,default=Saga.get_default_pk) startChapter = models.PositiveIntegerField() endChapter = models.PositiveIntegerField() class Clip(models.Model): description = models.CharField(max_length=200) arc = models.ForeignKey(Arc,on_delete=models.SET_DEFAULT,default=Arc.get_default_pk) chapter = models.PositiveIntegerField() viewers = models.ManyToManyField(User, through='ClipViewer') author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True, related_name='author_of') Basically all Sagas have a set of associated arcs and every arc has a list of associated clips. What I want to do is get my Sagas, Arcs and Clips through my API calls and then loop through each saga, getting the associated arcs for that saga and then loop through the arcs, getting the associated clips for that arcs, eg: Saga 1 has arcs 1,2,3 Arc 1 has clips 1 & 2 Arc 2 has clip 3 Arc 3 has clips 4 & 5 Saga 2 has arc 4,5.... But templates seem too limited to do this kind of querying, I can't do anything like get the list of associated arcs for a given saga or anything like that and being told: Because Django intentionally limits the amount of logic processing available in the template language, it is … -
Is there a way to add list in a django model class?
I'm a django beginner and trying to make a project from scratch. My models are : class Citizen(models.Model): name = models.CharField(max_length=64, unique=False) citizen_id = models.CharField(max_length=10, unique=True) def __str__(self): return '{} by {}'.format(self.name, self.citizen_id) class Manager(models.Model): name = models.CharField(max_length=64, unique=False) manager_id = models.CharField(max_length=10, unique=True) def __str__(self): return '{} by {}'.format(self.name, self.manager_id) class Message(models.Model): sender = models.ForeignKey(Citizen, Manager, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(Citizen, Manager, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1200) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) class Centre(models.Model): pass In Centre , there's gonna be one manager and then a lot of citizens. What should I do here? Should I add a list of citizens? Is that possible? -
Why aren't failed Django queries more descriptive?
A python dictionary will throw a keyerror that describes what key was searched for and failed. Why does running .objects.get() on a queryset not describe the parameters passed in that failed to return a model, or returned more than one? Is this something that could be added to Django.db? -
My custom save_user function in allauth does not work
I am trying to store the profile picture of the user when he is logging in with google. So, I have modified the save_user in following way: from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): print("called1") def save_user(self, request, user, form, commit=True): print("called2") user = super(MyAccountAdapter, self).save_user(request, user, form, commit=False) data = form.cleaned_data user.picture = data.get("picture") print("called3") user.save() print("called4") pass But for some reason my modified save_user doesn't work. It is to be noted that I used print to know if the code inside my modified function was called. But When I run the application I only get called1 and called4 printed in compiler but not called3 and called2. Note: I have already added ACCOUNT_ADAPTER in settings.py. -
How to pass a function with parameters from view to template in Django?
I am passing a function from views.py to a template in Django. This function takes a date argument and returns the difference between it and today's date views.py: def days_until(date1): td = datetime.date.today temp = date1 - td return temp.days def index(request): entries = Entry.objects.all() return render(request, 'index.html', {'entries' : entries, 'days_until' : days_until}) index.html: {% for entry in entries %} <div> {{ days_until(entry.date) }} </div> {% endfor %} This code doesn't work and returns this error: Could not parse the remainder: '(entry.pwExp)' from 'days_until(entry.pwExp)' I'm assuming that I am not calling days_until incorrectly. How should I be passing entry.date into this function? -
Django admin: Filter field by range
Hi i have a model called Person. Person has fields like name/surname and age. Now what I want to achieve is to have a filter in django admin that can filter age in some custom ranges so 10-15 after reading some posts my best shoot is class RangeFilter(SimpleListFilter): title = 'Age filter' parameter_name = 'age' def lookups(self, request, model_admin): return [ (1, '0-5'), (2, '5-10'), (3, '10-15'), (4, '15-20')] def queryset(self, request, queryset): filt_age = request.GET.get('age') return queryset.filter( age__range=self.age[filt_age] ) but this yields an error 'RangeFilter' object has no attribute 'age_dict' -
adding in get_context_data of a class-based view an external script
I have a python script in a page which I would like to exploit in a class-based view pages/textutile.py class Palindrome: def __init__(self, mot): self.mot = mot def getMot(self): i = 0 y = 0 while(i < len(self.mot)): envers = (len(self.mot)-1-i) c = envers+y-envers i = i+1 y = y+1 if(self.mot[envers] == self.mot[c]): return f"{self.mot} est un palindrome" else: return f"{self.mot} n'est pas un palindrome" I import it into pages/views and i have this class based view to which i would like to insert this code to display it in palind_detail view pages/views.py from .texteUtile import Palindrome class PalindDetailView(DetailView): model = Palind context_object_name = "palind" template_name = "pages/palind_detail.html" the code i would like to insert in get_context_data foo = Palind.objects.all() newClass = Palindrome(foo) selectmot = newClass.getMot() # i need get variable "selectmot" in context it's a simple test on words to insert in the database (the name of the field is "mot") it tests if the word is a palindrome. and displays it in palind_detail.html. but the main thing is to understand how get_context_dat works for class-based views Merci -
How to connect React Native app to Django REST API
I'm in the process of connecting my React Native UI to Python Django backend using REST framework and unsure of how to go about fetching the data from backend. I used the fetch(URL) as you can see in the SS below: The error I get: I also added my phone as an adb device and connected it through a USB cable before running the app, but same issue. Any suggestions as to how to go about React Native UI and Python Django REST API integration? -
Django crispy forms - bootstrap4 table_inline_formset template rendering extra row on top
I am using the bootstrap4/table_inline_formset.html template in a FormHelper from django-crispy-forms. The table is rendered correctly in the template, but an extra form always appears at the beginning of the table, which is not visible when submitting the form. forms.py: class MetricForm(forms.ModelForm): class Meta: model = Metric exclude = ['auto_value','occurrence'] class MetricFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(MetricFormSetHelper, self).__init__(*args, **kwargs) self.add_input(Submit('submit', 'Submit', css_class="btn btn-success")) self.template = 'bootstrap4/table_inline_formset.html' views.py: @login_required def create_occurrence(request, pk): try: site = Site.objects.get(id=pk) except Site.DoesNotExist: raise Http404("Site does not exist") form = OccurrenceForm(request.POST or None, initial={'site':site}) MetricFormset = modelformset_factory(Metric, form=MetricForm, extra=3) formset = MetricFormset(queryset=Metric.objects.none()) helper = MetricFormSetHelper() if form.is_valid(): occurrence = form.save(commit=False) occurrence.added_by = request.user occurrence.site = site occurrence.save() form.save_m2m() metric_formset = MetricFormset(request.POST) if metric_formset.is_valid(): for metric_form in metric_formset.forms: if all([metric_form.is_valid(), metric_form.cleaned_data != {}]): metric = metric_form.save(commit=False) metric.occurrence = occurrence metric.save() messages.success(request, "Occurrence created successfully.") execute_from_command_line(["../manage_dev.sh", "updatelayers", "-s", "archaeology"]) return redirect(occurrence.get_absolute_url()) context = { 'form': form, 'site':site, 'formset':formset, 'helper': helper, } return render(request, "archaeology/occurrence_form.html", context=context) template: ... <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <h4>Metrics</h4> {{ formset.management_form }} {% crispy formset helper %} {% if form.instance.pk != None %} <a class="btn btn-danger" href="{% url 'delete_occurrence' occurrence.id %}">{% trans "Delete" %}</a> {% endif %} </form> ... Any … -
Django NoModuleFoundError occurs only when adding a valid path to urls.py of my project folder
I have set up a Django project according to Victor Freitas' excellent post on production ready Django boilerplate here https://simpleisbetterthancomplex.com/tutorial/2021/06/27/how-to-start-a-production-ready-django-project.html It took me a day to refactor my whole project with 7 apps to fit into that boilerplate. All was fine and with everything working until I started developing my urls paths and templates. For some reason when adding a url path to main urls.py file within the main project folder Django fires me a NoModuleFoundError stating 'ModuleNotFoundError: No module named 'categories' . Categories is the name of my app and it is properly installed in base.py config file. Code below: # SIGP3A/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # path('categories/', include('categories.urls')), # <-- THIS LINE RIGHT HERE ] If I uncomment the above pointed line I get the error message. If I comment it out it passes Django checks. See bellow bits and pieces of the code that I believe are relevant to the question: # SIGP3A/Comps/categories/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.categories, name='categories'), ] See below my installed apps where categories is included. Note Comps is INSIDE main project folder and it is … -
In Django I use request.POST and return JSONResponse but the url shows HttpResponse error. I don't want to use render
I'm using Ajax to submit a POST. In views.py I have the following: def color(request): if(request.POST.get('result_data',False)): mylist= request.POST['mydata'] mylist= listt.split(",") request.session['var1'] = mylist[0] request.session['var2'] = mylist[1] return JsonResponse({'success':True}) In url I defined color/, so when I go to localhost:8000/color it shows error: "didn't return an HttpResponse". I should use instead return render(request,'app/color.html',{}) but I do not have a color.html file. I actually don't want to have one. All I want is to post a variable and use it as a session, so how can I avoid using render() and creating the html file? Thanks -
How can i give the user 1 times permission to access the page
How can i give the user 1 times permission to access the page(like a exam page). There is a one problem. When i resize page, its must be reload. Also when he goes to another page couldnt return the exam page like with back button or try to return from url. like a page -> b page x- a page -
Migrating Data from old Database to new one
i am currently building a new version of a web application and i got an existing database. Now i want to have a new database for the new version, since the existing database is not quite optimal. I can't alter the old one tho, since it's currently still used in production. Can i somehow build a new database table and fill it with altered versions of data from the old one? For example lets imagine i got an old model: class UserNumbers(model.Model): id=models.IntegerField(primary_key=True) name=models.CharField(max_length=50, blank=True, null=True) phone_number1=models.CharField(max_length=50, blank=True, null=True) phone_number2=models.CharField(max_length=50, blank=True, null=True) phone_number3=models.CharField(max_length=50, blank=True, null=True) and want to populate my new model: from phone_field import PhoneField class User(model.Model): id=models.IntegerField(primary_key=True) name=models.CharField(max_length=50, blank=True, null=True) class UserNumbers(model.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) phone_number = PhoneField(help_text='Contact phone number') comment = models.CharField() so is there some way like: for data in UserNumbers_old: User_new(id=data.id,name=data.name).save() if data.phone_number1: UserNumbers_new(user_id=data.id,phone_number=data.phone_number1,comment="") ... -
Django Redirect URL that shows in Address Bar
Happy Friday, everyone, How would I be able to use a Django redirect to where it would catch mixed-case URLs and redirect to the page that matches the lowercase version of what the end-user had in their request URL. For example, having "http://www.acme-co.com/Acme" redirect to "http://www.acme-co.com/acme". We are using a CMS system that dispatches the incoming request to match one of the "Pages" in their Page model, so coding the view with lower() or another function to intercept the parameter is not an option (so I believe). Even in a situation like that one, how do I have the URL also change in the address bar, as well, versus just redirecting them to the proper view? I believe I've found where the request address comes in and have been successful in redirecting incoming requests (though I imagine with the expertise of this forum, someone probably has a better way and more efficient of accomplishing the same thing, so will graciously accept any advice) and I'm stuck on changing what's in the address bar. Thank you in advance. -
One membership for each user for each club
I'm creating models to manage clients and sports centers. Each customer can be enrolled in several centers only once of course. how should i proceed for this? class Membership(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='memberships') club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='memberships') points = models.PositiveIntegerField(default=0, blank=True, null=True) sub_date = models.DateField(auto_now_add=True) #other... If I proceed in this way it is possible to create multiple subscriptions of the user to the same club. How can I solve the problem? -
django form not saving despite success message
I have been trying to teach myself something new this week by following various tutorials on Google APIs. I am hitting a wall on the form saving bit, so helping you can help. Basically, I am trying to offer user the possibility to enter their first line of address for Google to then submit suggestions of addresses. This first bit works (when I enter the first line of an address, I get generated a list of suggestions). However, when I am trying to save the form, this doesn't seem to be saved anywhere. And I am not getting any error message either (if anything I am getting the a "success message" I am supposed to receive when the form is successfully submit). I thought there might be a field that is not getting being populated in the html. So I tried to empty one and tried to save. But on this occasion I received an error message, saying the field is missing. Which makes me thing this hasnt anything to do with the fields in the form but probably how I save my form in the views.py. I must admit I am way out of my comfort zone here (this … -
How to get post argument in django?
I am a complete beginner when it comes to web development. What I want to do is receive a command from the frontend and then print it in the backend to then use it for something else (that I haven't made yet). For the frontend, I use vuejs and send a post request to my django backend using axios like that: const send= {cmd:"cmd"}; axios.post('http://127.0.0.1:12345/app/', send).then(response=>this.rep=response.data); For my backend, here is the app.urls: urlpatterns = [ path('', views.test1, 'cmd', name='test1'), ] and my app.views: from rest_framework.views import APIView from rest_framework.response import Response def test1(request, cmd): print(cmd) return Response("ok!") My problem is that when I do that, I receive an error; the backend receives the post but I get: kwargs.update(self.default_args) ValueError: dictionary update sequence element #0 has length 1; 2 is required "OPTIONS /app/ HTTP/1.1" 500 78701 I tried without the cmd in path('', views.test1, 'cmd', name='test1'), but I had another error saying: TypeError: test1() missing 1 required positional argument: 'cmd' Any idea as to what is causing this error and how I could resolve it? -
Razorpay says seller cannot accept payments in (Live mode)
Im trying to implement razor pay in live mode on a Django Project, on clicking pay button it shows availabe options to pay, but when i select a option and proceed it says this seller cannot accept payments razorpay_client = razorpay.Client(auth=(settings.RAZOR_KEY_ID,settings.RAZOR_KEY_SECRET))[This is my output image][1] def cart(request): l = len(Itemcart.objects.filter(uname=request.session['username'][0])) if request.session.get('username') and l >=1: CurrentUser = "" try: CurrentUser = request.session['username'][0] except: pass CheckOutPrice = 0 try: for each in Itemcart.objects.all(): CheckOutPrice = CheckOutPrice + int(each.icprice) except: print("Error! no cart data found for current user") currency = 'INR' callback_url = 'paymenthandler/' Totalamount = int(CheckOutPrice * 100) razorpay_order = razorpay_client.order.create(dict(amount=Totalamount,currency=currency,payment_capture='0')) razorpay_order_id = razorpay_order['id'] context = {} context['razorpay_order_id'] = razorpay_order_id context['razorpay_merchant_key'] = settings.RAZOR_KEY_ID context['amount'] = Totalamount context['callback_url'] = callback_url return render(request,'cart.html',context=context) return render(request,'cart.html') def paymenthandler(request): print("123") if request.method == "POST": try: # get the required parameters from post request. payment_id = request.POST.get('razorpay_payment_id', '') razorpay_order_id = request.POST.get('razorpay_order_id', '') signature = request.POST.get('razorpay_signature', '') params_dict = { 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': payment_id, 'razorpay_signature': signature } # verify the payment signature. result = razorpay_client.utility.verify_payment_signature( params_dict) if result is None: amount = Totalamount try: # capture the payemt razorpay_client.payment.capture(payment_id, amount) # render success page on successful caputre of payment return render(request, 'paymentsuccess.html') except: # if there is … -
Why does my like button return a Json object { liked: true } but doesn't work with my ajax call in Django when a user clicks the like button
I have been trying to create a like button with calling an ajax function in Django, But somehow whenever i click on the like button it redirect me to different page with a json object that return {liked : true }. why am getting this issue! it's been a challenge for me to figure it out and does it having any thing to do with my javascripts or with my function in views.py how better can i do this to stop the effect! and make the page not to reload when users like! Here's my like function! def like(request, pk, c_slug=None): user = request.user if request.POST.get("operation") == "like_submit" and is_ajax(request=request): liked=get_object_or_404(Like,pk=pk) product = Product.objects.get(pk=pk, slug=c_slug) liked= False like = Like.objects.filter(user_like=user, product=product) if like: like.delete() else: liked = True Like.objects.create(user_like=user, product=product) resp = { 'liked':liked, } response = json.dumps(resp) return HttpResponse(response,content_type = "application/json") model.py class Like(models.Model): user_like = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_likes', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='user_likes', on_delete=models.CASCADE) like_date = models.DateTimeField(auto_now=True) This is my scriepts for ajax call <script> $(".like").click(function (e) { var id = this.id; var href = $('.like').find('a').attr('href'); e.preventDefault(); $.ajax({ url: href, data: {'liked': $(this).attr('name'), 'operation':'like_submit', 'csrfmiddlewaretoken': '{{ csrf_token }}'}, success: function(response){ if(response.liked){ $('#likebtn' + id).html("Unlike"); $('#likebtn' + id).css("color", "gray") } … -
How can a refresh_from_db and a manual get differ?
I am currently working on a project I am not very familiar with and trying to remove all of the mentioned reload methods which look like this: def reload(self): return self.__class__.objects.get(pk=self.pk) As they were added when refresh_from_db wasn't in Django yet, they are all over the place and used to get an updated model from the database. Changing the method to def reload(self): self.refresh_from_db() return self should in my understanding produce the same output. However when running the tests they fail because there are apparently changes. What I already investigated is if the refresh_from_db method is overwritten, but the model is a regular django.models.Model. -
cannot GET objects from database Django
i cannot get objects from my database. i'm getting nothing. in terminal i'm not getting error and i'm entering on website without problem. i want get information from . DT = Destination_Tour.objects.all() my Views.py def index(request): min_date = f"{datetime.now().date().year}-{datetime.now().date().month}-{datetime.now().date().day}" max_date = f"{datetime.now().date().year if (datetime.now().date().month+3)<=12 else datetime.now().date().year+1}-{(datetime.now().date().month + 3) if (datetime.now().date().month+3)<=12 else (datetime.now().date().month+3-12)}-{datetime.now().date().day}" citynames = Place.objects.all() slider = Slider.objects.all() DT = Destination_Tour.objects.all() if request.method == 'POST': origin = request.POST.get('Origin') destination = request.POST.get('Destination') depart_date = request.POST.get('DepartDate') seat = request.POST.get('SeatClass') trip_type = request.POST.get('TripType') citynames = Place.objects.all() if(trip_type == '1'): return render(request, 'base.html', { 'origin': origin, 'destination': destination, 'depart_date': depart_date, 'seat': seat.lower(), 'trip_type': trip_type, 'name':citynames, }) else: return render(request, 'base.html', { 'min_date': min_date, 'max_date': max_date }) context = { 'name':citynames, 'sd': slider, 'DT' : DT, } return render(request,'base.html', context = context) -
How to work with xml's in a request django
Is there a way I can work with files in a request on django? My app is going to allow users to upload XML files, to which I want to use XML minidom to parse them and then post the data into the db. is there a way I can do this without saving the uploaded file locally?