Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
There are some values Django cannot serialize into migration files
Cannot makemigrtions. ValueError: Cannot serialize: stories.validators.ValidateImageSize object at 0x7fb4e8c8b810 There are some values Django cannot serialize into migration files As I understood, we can't serialize class, anyway, how to solve this problem? field in model image = models.ImageField(upload_to=upload_location, validators=[ValidateImageSize('1 kb')])) validators.py class ValidateImageSize(object): ... -
Domain Port uWsgi Tutorial - uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html#about-the-domain-and-port
Am following the Tutorial here - as i was tinkering with my working Nginx config and messed things up . Now i have a very basic doubt . In the uWsgi docs here - https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html#about-the-domain-and-port Its mentioned that - This should serve a ‘hello world’ message directly to the browser on port 8000. Visit: http://example.com:8000 I substitute my own domain / FQDN , here -- http://digitalcognition.co.in:8001/dc/datasets_listView zilch - nothing ? My question - having gone through the tute till this stage , how does anything know yet whats my domain - i havent configured Nginx yet ? Total confusion. Someone kindly help thanks . -
How to auth using JWTTokenUserAuthentication
Henlo! App deps: djangorestframework-simplejwt==4.3.0, djangorestframework==3.10.3 I'm trying to auth User with JWTTokenUserAuthentication without using DB using shared SECRET_KEY. In my settings I have: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=120), 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(hours=12), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': SECRET_KEY, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': datetime.timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': datetime.timedelta(days=1), } For the views I use rest_framework_simplejwt.views.TokenObtainPairView. And in my app's urls: urlpatterns = [ path('test-token/', TokenObtainPairView.as_view(), name='token_obtain_pair') ] So, I'm making post request providing it with Bearer token and credentials as username and password. But I get message: { "detail": "No active account found with the given credentials" } What should I do to auth correctly? -
how to write serializer for joined model?
i have applied join on two tables with following query, VIEWS.PY class performance(viewsets.ModelViewSet): queryset = Leads.objects.select_related('channelId').values("channelId__channelName").annotate(tcount=Count('channelId')) serializer_class = teamwise_lead_performance_serializer but i am unable to catch response using this serializers, SERIALIZER.PY class channel_serializer(serializers.ModelSerializer): class Meta: model = Channels fields = ['channelName'] class performance_serializer(serializers.ModelSerializer): tcount = serializers.IntegerField() channel = channel_serializer(many=True, read_only=True) class Meta: model = Leads fields = ['tcount', 'channel'] i am getting the following, [ { "tcount": 88 }, { "tcount": 25 }, { "tcount": 31 }, { "tcount": 4 }, { "tcount": 1 }, { "tcount": 23 }, { "tcount": 2 }, { "tcount": 27 } ] expected response is, [ { "channelName": "abc", "tcount": 88 }, { "channelName": "def", "tcount": 25 }, { "channelName": "ghi", "tcount": 31 }, { "channelName": "qwe", "tcount": 4 }, { "channelName": "rty", "tcount": 1 }, { "channelName": "uio", "tcount": 23 }, { "channelName": "psa", "tcount": 2 }, { "channelName": "dfg", "tcount": 27 } ] i have tried the following, How to join two models in django-rest-framework why is it not getting the channelName in response? what am i doing wrong here? Thank you for your suggestions -
ModuleNotFoundError: No module named 'webpushapi'
I'm implementing a package called django-webpush in my project Ref: https://pypi.org/project/django-webpush/ Firstly, I installed this package using the command pip install django-webpush and it got installed successfully. Next in my INSTALLED_APPS in Settings.py I included the new application called web push. When I run python manage.py run server It tells me: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'webpushapi' -
django a particular view is getting triggered twice (GET/POST) both and only in chrome, firefox and postman requests trigger the view just once.W
get requests are javascript redirects just by changing window.location.href and post requests are ajax requests, same url in django url conf serves the two of them. The page is heavily populated with data, images and links etc. which do come as a response in get and post requests. On Chrome it executes the request twice, I cannot see it going twice in the Network tab on dev tools but at the terminal where I am running server I can see the view's print statements executing twice. I could have kept it fine like this, but then the first request goes with parameters and the second goes without the parameters(data to post) and the resultant page is always from the second request which is not exactly what the user is asking for. -
Unable to clear ImageField on form save
I'm able to save an image just fine to my imagefield, but I'm having trouble clearing an image field on a form on save. After the user clicks "Clear" and then clicks the save button, what gets saved to the ImageField (I'm actually using VersatileImage field, which is an extension of the ImageField) is the value of False. models.py class Customer(models.Model): name = models.CharField(max_length=100) image = VersatileImageField('image_gallery', upload_to=customer_files, null=True, blank=True) def __str__(self): return str(self.name) forms.py class UpdateCustomerDetailForm(forms.Form): name = forms.CharField(max_length=100, required=True) image = forms.ImageField(required=False) def __init__(self, *args, **kwargs): self.customer = kwargs.pop('customer',None) super(UpdateCustomerDetailForm, self).__init__(*args, **kwargs) self.fields['name'].initial = self.customer.name self.fields['image'].initial = self.customer.image views.py if form.is_valid(): customer.name = form.cleaned_data['name'] formimage = form.cleaned_data['image'] if formimage == False: customer.image.delete(save=True) else: customer.image = formimage customer.save() Thanks for your help! -
How to customize input to for generating JWT token using Django+GraphQL?
I'm using django-graphql-jwt (https://django-graphql-jwt.domake.io/en/latest/) to generate JWT token for authentication. The default setting for authentication in this package is to input username and password. But I need to authenticate through a third-party server. The process is like following: User goes to my frontend and click login. Then it goes to the third-party to input their username and password. This will return a ticket. My frontend will send the ticket to my backend (Django) and my backend will then validate this ticket with that third-party server. This will return the username and set a token to cookies (generated from django-graphql-jwt) if the ticket is valid. My question is that how could I customize the input of getting the token. I found the documentation here (https://django-graphql-jwt.domake.io/en/latest/customizing.html). But it seems no enough details for me to implement. Could anyone who has experience on this problem/ package provide some suggestions? Many Thank! -
Need help writing a Unit Test in Django
Good day everybody. I need to test a view, and I got stuck ( I am a django newbie). I got through all other url and view tests, but I'm really not sure how to write this one. I tried writing it on my own, I read through the testing docs, I even tried testing this using model_mommy ( but I got a custom HTML field in my models ) which is not supported by mommy. I tried with mommy Recipes, also without luck. I really gotta do this test today, it's a part of a task I was given. here is the view : class CommentCreateView(CreateView): def get(self, request, *args, **kwargs): context = {'form': CommentForm()} return render(request, 'news/add_comment_to_article.html', context) def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): article = get_object_or_404(Article, pk=kwargs.get('pk')) print(article) comment = form.save(commit=False) comment.post = article comment.save() return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk})) else: form = CommentForm() return render(request, 'news/add_comment_to_article.html', {'form': form}) and here are my models: class Article(models.Model): title = models.CharField('title', max_length=200, blank=True) slug = AutoSlugField(populate_from='title', default="", always_update=True, unique=True) author = models.CharField('Author', max_length=200, default="") description = HTMLField() is_published = models.BooleanField(default=False) article_text = HTMLField('Article text', default="") pub_date = models.DateTimeField(default=datetime.now, blank=True) article_category = models.ForeignKey(Category, on_delete="models.CASCADE", blank=True, null=True, default="") … -
Query multiple foreign keys in Django
I have two models Kits and Products: Models.py class Kit(models.Model): kit_name = models.CharField(max_length=255, default=0) kit_info = models.CharField(max_length=255, default=0) components_per_kit = models.IntegerField(default=0) product1 = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='kit_product1') product1_information = models.CharField(max_length=255, default=0) product1_quantity = models.IntegerField(default=0) product1_unitprice = models.IntegerField(default=0) product2 = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='kit_product2') product2_information = models.CharField(max_length=255, default=0) product2_quantity = models.IntegerField(default=0) product2_unitprice = models.IntegerField(default=0) product3 = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='kit_product3') product3_information = models.CharField(max_length=255, default=0) product3_quantity = models.IntegerField(default=0) product3_unitprice = models.IntegerField(default=0) product4 = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='kit_product4') product4_information = models.CharField(max_length=255, default=0) product4_quantity = models.IntegerField(default=0) product4_unitprice = models.IntegerField(default=0) product5 = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='kit_product5') product5_information = models.CharField(max_length=255, default=0) product5_quantity = models.IntegerField(default=0) product5_unitprice = models.IntegerField(default=0) kit_client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='kit_owner') def __str__ (self): return self.kit_name class Product(models.Model): category = (('Metal', 'Metal'), ('Wood', 'Wood'), ('Plastic', 'Plastic')) product_id = models.IntegerField(default=0) product_name = models.CharField(max_length=255, default=0) product_category = models.CharField(max_length=255, default=0, choices=category) product_quantity = models.IntegerField(default=0) product_owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='product_owner') and in my views.py I am querrying the products like this: def load_product (request): kit_id = request.GET.get('kit') product1 = Product.objects.filter(kit_product1=kit_id) product2 = Product.objects.filter(kit_product2=kit_id) product3 = Product.objects.filter(kit_product3=kit_id) product4 = Product.objects.filter(kit_product4=kit_id) product5 = Product.objects.filter(kit_product5=kit_id) products = list(chain(product1, product2, product3,product4,product5)) print("products are", products) return render(request, 'packsapp/employee/kit_product_list_options.html', {'products': products}) Is there any other way I can access all the products in the kit because these queries return the following: products are [<Product: 1111::Plastic … -
How to Annotate Specific Related Field Value
I am attempting to optimize some code. I have model with many related models, and I want to annotate and filter by the value of a field of a specific type of these related models, as they are designed to be generic. I can find all instances of the type of related model I want, or all of the models related to the parent, but not the related model of the specific type related to the parent. Can anyone advise? I initially tried parent.annotate(field_value=Subquery(related_field.objects.get( field__type='specific', parent_id=OuterRef('id'), ).value))) But get the error This queryset contains a reference to an outer query and may only be used in a subquery. When I tried parent.annotate(field_value=Q(related_field.objects.get( field__type='specific', parent_id=F('id'), ).value))) I get DoesNotExist: related_field matching query does not exist. which seems closer but still does not work. Is what I want to do even possible? -
Django having one to one and many to many rel in the same model
We want to having many to many and one to one relationship within the same model. Let me give an example. class Definition(models.Model): value = models.CharField(max_length=100) ... class Container(models.Model): name = models.CharField(max_length=30) container_specific_defn = models.OneToOneField(Definition, null=True, blank=True) definitions = models.ManyToManyField(Definition) As you can see a Container model have both 1to1 and m2m rel with Definition model. ie. I want Container can have any number of definitions but the defn which we are goinig to be added to definitions set should not be added to any container's container_specific_defn field. But the above model design allows a defn which was assigned to one contaioner's container_specific_defn field to be added to another container's definitions set. container_specific_defn = Definition.objects.create(value='container_specific') global_defn = Definition.objects.create(value='global') c1 = Container.objects.create(name='c1', container_specific_defn=container_specific_defn) c2 = Container.objects.create(name='c2') c2.definitions.add(container_specific_defn) c2.save() # [container_specific_defn] Do I need to change the model design? -
Can I maintain Database access results?
I'm setting up a django server, and want to maintain database access results. For example, I'm using infinite scroll on front end. When I reached the end, FE request data from Django. Then I want to keep the results in Django. Is it possible? Backend is django server and frontend is react-native. I considered using offset and seek method, but that wasn't what I wanted. I want to database access only once and maintain that results in Django. Likes React State -
[WinError 10061]sending email with dynamic email configuration?
Here I am trying to send html_email to users with the dynamic mail configuration and for this I have tried like this but it didn't worked. Before I was configuring email in my settings.py file and it was working perfectly. But After I tried like this it is not working. Now it throws: Django Version: 2.1.5 Exception Type: ConnectionRefusedError Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it How can I solve this? models.py class EmailConfiguration(models.Model): email_use_tls = models.BooleanField(default=True) email_host = models.CharField(max_length=250,default='smtp.gmail.com') email_host_user = models.CharField(max_length=250,default="your@email.com") email_host_password = models.CharField(max_length=250,default='pass_word') email_port = models.PositiveSmallIntegerField(default=587) views.py def register_user(request): form = RegisterUserForm() if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): user = form.save() # creating profile model with user data Profile.objects.create(user=user, name=name,....) config = EmailConfiguration.objects.last() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) #tried this: backend_email = backend.objects.last() # sending html_email to the user subject, from_email, to = "....", backend.email, user.email text_content = "..." site = get_current_site(request) html_content = render_to_string('send_email_user.html', {'user': user, 'site_domain': site,}) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() adding email_backed def create_email_backend(request): form = EmailBackendForm() if request.method =='POST': form = EmailBackendForm(request.POST) if form.is_valid(): form.save() messages.success(request,'created') return redirect('create_email_backend') return render(request,'create_email_backend.html',{'form':form}) -
How to print list as separarte strings in django template
I want to print list as a separate strings in html For example: ['one','two','three'] output- one,two,three for loop didn't work it prints one letter per line instead one item I tried slugify but it ads dashes {{item.notes|slugify}} -
Little problem with dynamic mail configuration?
Here i am trying to send a html email to recently registered users and I tried like this. Before the email configuration was in settings.py file for sending email .Now I am trying to make this configuration dynamic and I tried like this but I got problem while getting the pk of an EmailConfiguration model in my register_user functinon because the function doesn't have any pk parameter in url patterns so I think there might be problem.So what will be the best for solvig this? How can i use my dynamic mail configuration here ? models.py class EmailConfiguration(models.Model): email_use_tls = models.BooleanField(default=True) email_host = models.CharField(max_length=250) email_host_user = models.CharField(max_length=250) email_host_password = models.CharField(max_length=250) email_port = models.PositiveSmallIntegerField(default=587) views.py def register_user(request): form = RegisterUserForm() if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): user = form.save() # creating profile model with user data Profile.objects.create(user=user,...) # how can i get the pk of EmailConfiguration config = EmailConfiguration.objects.get(pk=pk) backend = EmailBackend(host=config.email_host, port=congig.port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) # sending html email to user subject, from_email, to = ".....", ?????, user.email text_content = "..." site = get_current_site(request) html_content = render_to_string('send_email_user.html', {'user': user, 'site_domain': site,}) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() -
How to host Django website on my local Linux server with custom domain?
I have made a Django website which I want to make available to the all internet users around the world. I want to host this site on my Linux based computer with a custom domain name which I have already purchased. I have installed Ubuntu server 18.04 LTS on Virtual Box with Router a based internet connection without static IP. I want to use Nginx, Gunicorn, Redis for this Django app. But I can't figure it out how to use custom domain here. Guys could you please help me to solve this problem? Thanks in advance! -
Jquery Changing Boolean Checkbox to Dropdown?
In a django project I'm looking to hide/unhide a field when a checkbox is selected or unselected. It seems to be working, but it seems the jquery is changing the boolean field which I've defined from a checkbox to a dropdown. How can I prevent this from happening? Below is_phyto is the field I want to remain as a checkbox. <script> $(function () { $('#is_phyto').change(function () { if ($('#is_phyto').is(':checked')) { $("#p_consignee").show(); } else { $("#p_consignee]").hide(); } }).change(); }); </script> -
How to deploy a Django website w/ static files in DigitalOcean
I am following the DigitalOcean tutorial on deploying a website with CSS files. https://www.digitalocean.com/community/tutorials/how-to-set-up-a-scalable-django-app-with-digitalocean-managed-databases-and-spaces I already have my own website files that I made with Django, but my folder/file structure is different than that of the example project: https://github.com/do-community/django-polls For example, my website only has two main folders, and my index.html file is in a completely different folder than that of the example. Is it possible for me to just swap the files in the example project with my own (take out the css,index.html,settings.py, etc files in the example and put mine in those folders)? Will the website still deploy correctly if I only copy the files in, but now they are in different folder structure? -
How to use custom table for authentication in django rest framework
I have an existing Customer table and i create model for it from django.contrib.auth.models import AbstractUser class Customer(AbstractUser): user_id = models.AutoField(primary_key=True) username = models.CharField(max_length=100,unique=True) password = models.CharField(max_length=32) first_name=models.CharField(max_length=250) last_name=models.CharField(max_length=250) email=models.EmailField(max_length=250) country=models.CharField(max_length=250) city=models.CharField(max_length=250) zip=models.CharField(max_length=250) state=models.CharField(max_length=250) territory=models.CharField(max_length=250) phone=models.CharField(max_length=15) address =models.TextField(blank = True) profile_pic= models.ImageField(upload_to='media/image',default='') notes = models.TextField(blank = True) #date_added=models.DateField() token=models.CharField(max_length=32) is_active= EnumChoiceField(enum_class=ChoiceTypes , default=ChoiceTypes.active) class Meta: db_table="customer" And also changed default user model in Settings.py AUTH_USER_MODEL = 'Myapp.Customer' I manually added last_login, is_superuser, is_active, is_staff, date_joined columns to Customer table. I create a super user through command line and the data was inserted into Customer table. But when i check the login api, it raised some strange error Postman Screenshot -
How can I use Django model filter to query objects from my database if a fieldname is present in a string
How can I use django query for objects by checking if it's fieldname is present in a string using objects.filter(). Like, if I wanted to filter using a fieldname named "Foo" if it was in the string "Foo Bar". I tried the following line but of course it does not work: # name = Foo obj.objects.filter(name__in='Foo Bar') # Empty Query list -
Slow execution of for loop for(django or raw queryset) for more than 1000 results
I am not able to get more than 1000 results in ajax request(Server gets timed out for big data results). I wrote a simple query here query = '''SELECT l.id, l.timestamp, m.dname, m.user_id FROM leaduser l LEFT JOIN manager_detail m ON m.user_id=l.manager_id LEFT JOIN LATERAL (SELECT user_id AS log_id FROM lead_user_logs WHERE user_id=l.id ORDER BY TIMESTAMP ASC LIMIT 1) ll on TRUE ''' And now the for loop: arr=[] for lead in leads: new_dict = { 'name': '<a href="{}">{}</a>'.format(lead.get_absolute_url(), lead.name), 'phone': lead.phone, 'manager': lead.dname, 'clinic': lead.pname, 'dietitian': lead.dname, 'doj': localtime(lead.timestamp).strftime('%d-%m-%Y'), 'time': localtime(lead.timestamp).strftime('%I:%M %p'), 'sourcece': lead.source, 'country': lead.address['Country'], 'state': lead.address['State'], 'city': lead.address['City'],} arr.append(new_dict) I am not able to find what is wrong here(Loop is getting slow down when accessing to db columns) -
How can I change the stripe checkout form with a sign up or login form
My ecommerce website is set such that it's only through stripe checkout an order is created. Is there an option to replace the checkout form with a sign up or login form for new and returning clients respectively. -
Django request.user in model property
I am working on a simple chat app in which two users can participate. Based on the request.user I try to switch who of the two the other user is depending on who is logged in. The thing is that in the template I feel bound to use chat.other_user, which to my knowledge, can only be added as a property to the model. Now, I know this is an anti-pattern, the model should not carry request-specific properties. I just don't know how else to solve it.. I've considered context_processors, template_tags, remodeling. One of the solutions I've found is to use middleware to store request.user in a variable, but that doesn't sound right to me. The following code will not work but gives an idea of what I am trying to do: class Chat(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name='+', on_delete=models.PROTECT) user2 = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name='+', on_delete=models.PROTECT) start_time = models.DateTimeField(auto_now=True) def other_user(self, request): if request.user == self.user1: return self.user2 elif request.user == self.user2: return self.user1 {% for chat in chat_list %} <p>Chat with: {{ chat.other_user.username }}</p> {% endfor %} I tried to make it work with class-based views but I saw no way so I ended up doing the following. However, this … -
Django ORM , Dispay data to html table, the right way
my table html template, <table> <thead> <tr> <th>cars</th> <th>leasing</th> <th>sell</th> </tr> </thead> <tbody> {% for produkti in carsleasing %} <tr> <td>{{ produkti.choice_text }}</td> <td>{{ produkti.totals }}</td> <td>{% for produkti in carssell %} {{ produkti.total }} {% endfor %}</td> </tr> {% endfor %} </tbody> </table> Third column, it shows the data incorrectly, it must be the first line value 3 and the second line value 4