Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get Django values_list to return value of display override and not the actual value?
I noticed that when calling values() or values_list() one a queryset returns the normal value in the field and not the display value I'd like. Is there a way to manupilate the display value of the field while creating a result that is a list of list of the queryset? class FooBar(models.Model): ... foo_bar = models.CharField(_("foo"), choices=[(1, 'foo'), (2, 'bar')]) def get_foo_bar_display(self): return "something" def get_foobar(user): foobar = FooBar.objects.filter(user=user).values_list(.., 'foo_bar') foobar = list(map(list, foobar)) return foobar It always returns the foo_bar original value and not the display value. -
Add Index on field of AbstractClass
I have created one abstract model which provides default timestamp and I want to create Index on the field declared in that model Parent Model class CommonModel(models.Model): """ Provides default timestamp model """ updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True Child Model class EBUser(CommonModel): name = models.CharField(max_length=128, blank=False, null=False) work_email = models.CharField(max_length=128, blank=False, null=False) phone = models.CharField(max_length=20, blank=False, null=False) class Meta: db_table = 'user' I want to apply index on created_at field P.S: I'm using django==2.0.5, djangorestframework==3.8.2, python 3.6.5 -
Python Django /w Microsoft Graphs - I keep getting value error "state missing from auth_code_flow"
Python Django /w Microsoft Graphs - I'm following this Microsoft Tutorial for building Django apps with Microsoft Graph (using it on my existing Django webapp), and I am having an issue with authentication: https://docs.microsoft.com/en-us/graph/tutorials/python I'm on the step 'Add Azure AD authentication' and, after implementing, I hit the sign in button and enter credentials...and I keep getting value error "state missing from auth_code_flow". The "callback" method is only making it to result=get_token_from_code(request) and then fails. Here is the get_token_from_code method: def get_token_from_code(request): cache = load_cache(request) auth_app = get_msal_app(cache) # Get the flow saved in session flow = request.session.pop('auth_flow', {}) result = auth_app.acquire_token_by_auth_code_flow(flow, request.GET) save_cache(request, cache) return result What I'm trying to do is eventually access excel online from my webapp. Any help is greatly appreciated! -
how to return username instead of his ID rest framework
working fine but instead of name getting id number only views.py class createtweet(CreateAPIView): queryset = Tweets.objects.all() serializer_class = TweetsSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) serializers.py class TweetsSerializer(serializers.ModelSerializer): class Meta: model = Tweets fields = '__all__' pls give me a way to return username instead of id -
Django add id field to the model if I have primary key
I need create model that have uuid field set as primary key and id field: class SomeModel(models.Model): id = models._________ ? increment=1 unique=true uuid = models.CharField(max_length=36, unique=True, default=uuid4, editable=False, primary_key=True) -
['“27.10.2016” value has an invalid date format. It must be in YYYY-MM-DD format.']
issue_date = models.DateField(blank=True, null=True) close_date = models.DateField(blank=True, null=True) How to solve? -
=== operator not working inside an html element in Django template
This is my dashboard view in views.py def dashboard(request): return render(request, "account/dashboard.html", {"section": "dashboard"}) This a piece of code in my template. <li {% if section == "dashboard" %} class="selected" {% endif %}> <a href="{% url " dashboard" %}">My dashboard</a> </li> I'm getting this error when i try to access the page. Could not parse the remainder: '=="dashboard"' from 'section=="dashboard"' -
creating a django model which will retain the otherwise deleted (CASCADED) model instances(Like a Watchlist)
I created a model called "Post", another called "Event" and finally "Watchlist". Now, each post is associated with an event.When an event is complete, that instance of the event model is deleted, and with it, the post model is CASCADED. What i want is, for the Post instance to be deleted if the Event is deleted, but retained if the Post is added to Watchlist even after the event is over: My Models right now are: class Post(models.Model): title = models.CharField( max_length=100, validators=[MinLengthValidator(3, "Title must be greater than 3 characters")] ) event = models.ForeignKey(Event, on_delete=models.CASCADE, default=DEFAULT_EXAM_ID) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Event(models.Model): admin = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) participants = models.ManyToManyField(User, related_name="registered") class Watchlist(models.Model): post = models.ManyToManyField(Post, related_name="saved") owner = models.ForeignKey(User, on_delete=models.CASCADE) I am having trouble finding a proper way to implement the described feature. Can someone please help me with this? -
OperationalError at /admin/app/review/ no such column: app_review.startup_id
I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help here is my models.py from django.db import models from django.utils import timezone from django.utils.crypto import get_random_string import string import random code = get_random_string() class Startup(models.Model): code = models.CharField(max_length=12, default=code, unique=True) name = models.CharField(max_length=30) lead = models.CharField(max_length=50, unique=True) problem = models.CharField(max_length=100) solution = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Idea(models.Model): startup = models.ForeignKey(Startup, on_delete=models.CASCADE) summary = models.CharField(max_length=100) attachment = models.FileField(upload_to='attachments/idea') member = models.CharField(max_length=50, unique=True) date = models.DateTimeField(default=timezone.now) DRAFT … -
What is the proper way of unit testing a custom user model using choice field
I'm creating tests for a custom user model in Django that has a choice field. Is it possible to do this? -
UUID shown as integer in rest-framework
This is my model,serializer and 'admin` class UserData(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) pub_date = models.DateTimeField('date published',default=timezone.now) class UserDataSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('id','pub_date') def create(self, validated_data): user_data = UserData() user_data.save() return user_data class UserDataAdmin(admin.ModelAdmin): list_display = ["id","pub_date"] search_fields = ['id'] in admin screen id field is shown like but in rest-framework, id shown as integer. How can I fix this?? -
Python requests download zip file on request.post
I have two servers: First server send some files to second server and then get the zip file. I need get this zip file from response. My first server: files = {'file': ...} ceb_response = requests.post(ceb, files=files) My second server respond: return HttpResponse(open('db.zip', 'rb')) I need to save db.zip file in first server, how can I get the file from <Response [200]> and save file locally on first server? -
How to POST data to a common django view, what is a good approach for it using urllib module
As the title states, i'm using python urllib module to post my credentials to a generic django view for loging in, that's all. I tried some stuff based on the standard basic authentification pattern, modifying the authenticate header.... but all the same, it keeps throwing me a 403 forbidden code. i searched for a answer that address this matter, but as to me.... i couldn't find any. PD: I dont come across this problem only when authenticating, but also in POSTing any data to any view. Many thanks in advance. -
Getting Django Programming Error: column does not exist for a column that does exist
I'm fairly new to Django and still trying to figure things out. I'm trying to create a form to filter courses and populate an HTML dropdown with values from my Postgres database. My models.py from django.db import models # Create your models here. class AgeGroup(models.Model): agegroupid = models.AutoField(primary_key=True) agegrouptitle = models.CharField(max_length=50, blank=True, null=True) agegroupdescription = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'age_group' class Subjects(models.Model): subjectid = models.AutoField(primary_key=True) subjecttitle = models.CharField(max_length=50, blank=True, null=True) subjectdescription = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'subjects' class InstructorProfiles(models.Model): instructorid = models.AutoField(primary_key=True) instructorname = models.CharField(max_length=50, blank=True, null=True) instructordegrees = models.CharField(max_length=100, blank=True, null=True) instructorlongbio = models.CharField(max_length=1000, blank=True, null=True) instructorshortbio = models.CharField(max_length=500, blank=True, null=True) instructorphoto = models.CharField(max_length=1000, blank=True, null=True) class Meta: managed = False db_table = 'instructor_profiles' class Courses(models.Model): courseid = models.AutoField(primary_key=True) coursetitle = models.CharField(max_length=100) # instructorid = models.SmallIntegerField(blank=True, null=True) coursephoto = models.CharField(max_length=1000, blank=True, null=True) coursethumbnailphoto = models.CharField(max_length=1000, blank=True, null=True) credithours = models.DecimalField(max_digits=5, decimal_places=2) courseoneliner = models.CharField(max_length=200) coursedescription = models.CharField(max_length=500) instructor = models.ForeignKey(InstructorProfiles, on_delete=models.CASCADE) class Meta: managed = False db_table = 'courses' my views.py from django_mako_plus import view_function, jscontext from datetime import datetime, timezone from homepage import models as hmod from django.http import HttpResponseRedirect from django.shortcuts import render from django … -
Django: Add foreign key object to an existing object
Maybe a stupid question-- Two models A and B. A has a ForeignKey to B. I want to add another instance of B to an A instance. a = A.objects.create(b=b1) b2 = B.objects.create() So I add b2 to a like follows (so the error could be here): a.b = b2 When I print a.b I get <b1 object>, <b2 object>, which is what I want. But when I try to do a reverse b1.a_set.all(), I get an empty QuerySet. When I try to do a reverse for b2.a_set.all(), I get a in my QuerySet. Does b1 belong to a still? How can I get a to show up in the QuerySet for b1? -
read time not showing
I was trying to add a field "read_time" in my blog created by django3.1.7 I assigned the value to "instance.read_time", but it was still the default value 0 in models.py: class Post(models.Model): read_time=models.IntegerField(default=0) def pre_save_post_receiver(sender,instance,*args,**kwargs): if not instance.slug: instance.slug=create_slug(instance) if instance.content: instance.read_time = get_read_time(instance.get_markdown()) pre_save.connect(pre_save_post_receiver, sender=Post) in views.py, I try to print out related variables: print(get_read_time(instance.get_markdown())) print(instance.read_time) here's what's showing on my terminal: 1 0 Therefore, get_read_time(instance.get_markdown())=1, but instance.read_time =0. The value seemed not successfully passed onto instance.read_time. What's the problem guys? Thanks in advance! -
django: UserCreationForm: add_error to both passwords when pass validation fails
curretly in UserCreationForm (django.contrib.auth.forms) Django has def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) i want both the password fields to be shown error, when password validation fails how can i do this i tried def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) self.add_error('password1', error) But this does not work -
Django: Add another foreign key object to existing object
Probably a dumb question-- I have a model A object that has a ForeignKey to model B. When I create an A object, I include the foreign key. How can I add another B reference to my model A. Sample code: a = A.objects.create(b=b) b2 = b2.objects.create() # How can I add b2 to a? -
Using uuid.uuid4() as default value
I want to make model like import uuid class UserData(models.Model): id_key = # give uuid.uuid4() as default value pub_date = models.DateTimeField('date published',default=timezone.now) When UserData is made in script, id_key value should be made automatically. ud = UserData() ud.save() I guess I should make a function as default value though, I am not clear yet. how can I make this?? -
Django Testing - How can I patch multiple external API calls in a single function?
I have a function in a class that makes two separate, distinct GET requests to an external API. I'm not sure how I could go about patching each individual external call. Say my function is this (which lives under MyClass in myclass.py: def combined_requests(): a = requests.get("/a") b = requests.get("/b") return a.data + b.data Normally, if it was a single call I could do: def test_case(self): with mock.patch('myclass.requests') as mock_requests: mock_requests.get.return_value = 1 MyClass.single_request() But since I have two request calls, I'm not sure how I could patch each one within that combined function. Is this even possible to do? Thanks! -
how to get information for specific user in Django ( i wanted to get Appointment history for specific user who is now logged in )
#for for adding appointment def book_appointment(request): if request.method=="POST": specialization=request.POST['specialization'] doctor_name=request.POST['doctor'] time=request.POST['time'] app=Appointment(specialization=specialization, doctor_name=doctor_name, time=time) app.save() messages.success(request, "Successfully Appointment booked tap on view appointment for status") return redirect('home') #view appointment history def appointmentInfo(request): appts= Appointment.objects.all() return render(request,'home/view_appointment.html',{'appoints':appts}) #login def handeLogin(request): if request.method=="POST": # Get the post parameters loginusername=request.POST['loginusername'] loginpassword=request.POST['loginpassword'] user=authenticate(username= loginusername, password= loginpassword) if user is not None: login(request, user) messages.success(request, "Successfully Logged In") return redirect("home") else: messages.error(request, "Invalid credentials! Please try again") return redirect("home") return HttpResponse("404- Not found") return HttpResponse("login") -
Django not using DEFAULT_FROM_EMAIL
I'm trying to send emails with Django using SendGrid, that uses a Gmail account. I'm deploying the website on heroku. My settings.py file is as follows: SENDGRID_API_KEY = 'api key here' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 465 EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = 'myapp.api.test@gmail.com' However the DEFAULT_FROM_EMAIL variable doesn't seem to work. When trying to send an email, I get the error The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements However I already checked and my Sender Identity was validated with Single Sender Verification . I know DEFAULT_FROM_EMAIL isn't activated, as in the error log on line /app/.heroku/python/lib/python3.7/site-packages/django/core/mail/__init__.py when the error occurs I know the variable from_email is apikey, when it should be myapp.api.test@gmail.com. What is wrong? -
Custom User Model versus Django User Model
I am making a web application using Django as my backend, and I was wondering what the best practice is when dealing with models representing user account information (username, password, email, etc.). I am aware of an existing User model, as well as the practice of creating a custom user model by subclassing AbstractUser. However, I am confused as to how this is any different than subclassing models.Model and creating my own user model from scratch. Does anyone have advice as to what is best practice in this situation? -
Using "When" in a Django annotation, with a many-to-many relationship, returns more rows than it should
I have three models defined like this: class Equipment(models.Model): hostname = models.CharField(max_length=128) class Interface(models.Model): internal_ip = models.GenericIPAddressField() index = models.IntegerField() equipment = models.ForeignKey("Equipament", on_delete=models.CASCADE) class Event(models.Model): equipment = models.ForeignKey("Equipment", on_delete=models.CASCADE) index = models.IntegerField(null=True) datetime = models.DateTimeField(auto_now=True) When an Event is created, it may have an index, but it also may not. This index refer to the index of the Interface. events = Event.objects.all() events = events.annotate(interface_ip=Case( When(Q(index__isnull=False) & Q(equipment__interface__index=F('index')), then=F('equipment__interface__internal_ip')), output_field=models.GenericIPAddressField() )) When I apply this annotation, the events get multiplied by the interfaces the equipment has. This makes sense, because it's evaluating which interfaces, in the given equipment, match the index specified by F('index'). How can I simply exclude the ones that don't match? From my point of view, Q(equipment__interface__index=F('index')) should compare if the interface__index equals the index, and jump if it doesn't (on the other hand, I know it makes sense, since it has a default value of None, when it doesn't match). I wish I'd have control over how the Events get inserted on the table, but unfortunately I don't, since it's an external system making direct inserts on the MySQL database, and they simply get the index and throw it in the "index" field. -
Reverse for 'edit' not found. 'edit' is not a valid view function or pattern name
Internal Server Error: /wiki/Python Traceback (most recent call last): File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Bappy\desktop\web50\projects\2020\x\wiki\encyclopedia\views.py", line 21, in entry return render(request, "encyclopedia/entry.html", { File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\defaulttags.py", line 446, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\Bappy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'edit' not found. 'edit' is not …