Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multiple parameter in get request in django
url.py urlpatterns = [ path('api_doc/', schema_view), path('admin/', admin.site.urls), # regex for swagger creation path(r'^request.GET.get(‘tag’)&request.GET.get(‘order_by’)', views.QuestionList.as_view()), # path(r'^?tag={tag}&order_by={name}', views.QuestionList.as_view()), ] This is mu url.py file and i a trying to input "tag" and "order_by" in url in swagger but it's not working? i have tried above url options In the last one "?" is not reconized by url. -
foreignkey assignment error python django model
models.py i have create foreignkey in table paymentsDetails i have stripe payment method which is working when user login session is created and by using session value i get the primarykey of that user by using 'ORM' method and then assign this primary key of specific user into the paymentdetails models field named as user_account_id but i am getting error that i cannot assign 1 to PaymentsDetail.User_account_id must be a instance of UserAccountModel class UserAccountModel(models.Model): ContactEmail = models.EmailField(max_length=30) FirstName = models.CharField(max_length=30) LastName = models.CharField(max_length=40) Counrty = models.CharField(max_length=50) Phone = models.IntegerField() ChooseUserName = models.CharField(max_length=30) password = models.CharField(max_length=32) EnterCaptcha = models.CharField(max_length=4) payments = models.BooleanField(max_length=6, default=False) showsponsor = models.CharField(max_length=30, default=False) RegisteredDate = models.DateTimeField(auto_now_add=True, blank=True) ActivationOn = models.DateField(auto_now_add=False,blank=True) expiry_date = models.DateField(auto_now_add=False,blank=True) def __str__(self): return self.FirstName + ":" + self.ChooseUserName class PaymentsDetail(models.Model): refrer_name = models.CharField(max_length=32,default="", editable=False) sponser_name = models.CharField(max_length=32) status = models.CharField(default='comped', max_length=32) s_id = models.CharField(max_length=32) registered = models.DateTimeField(auto_now_add=True) activated_date = models.DateField(auto_now_add=False) Due_Date = models.DateField(auto_now_add=False) payment = models.CharField(default='$',max_length=32) User_Account_id = models.ForeignKey(UserAccountModel, on_delete=models.CASCADE, default=True, editable=True) addprogrameReference = models.ForeignKey(AddProgramModel, on_delete=models.CASCADE, default=True, editable=True) class Meta: ordering = ['User_Account_id', 'addprogrameReference'] def str(self): return self.refrer_name + ":" + self.user_account i am getting the error cannot assign 1 to PaymentsDetail.User_account_id must be a instance of UserAccountModel views.py print("user payment"+str(charge.amount)) pays = … -
How to write exception for ProxyConnetionError (errno - 10060, can't connect to proxy) for a Django project
Can anyone please help me how to write exception for a ProxyConnectionError? I have tried following code in Django project after browsing internet from aiohttp_socks import ProxyError try: return render(request,"data.html") except ProxyError: return HttpResponse("{Exception: check proxy settings}") -
Django rest-framework filter models by the name of other models connected with foreign key
class Genre(models.Model): name = models.CharField(unique=True,max_length=255) def __str__(self): return self.name class BlogText(models.Model): mytext = models.TextField(null=True) genre = models.ForeignKey(Genre, on_delete=models.CASCADE,null=True,blank=True) pub_date = models.DateTimeField('date published') Each BlogText has Genre. Now I can filter BlogText by contains mytext = filters.CharFilter(lookup_expr='contains') then I want to filter BlogText models by blogtext.genre.name I googled around but not found the reference other than CharFilter Contains. (even can't find IntFilter... I try to filter genre id directly....) How can I make it?? -
How do i disregard a django filter field if the field is empty?
So, i started to code a filtering system to my django application. It goes like this class Person(models.Model): first_name = models.CharField(max_length = 50) middle_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) i wanted to filter which Person has a field containing x value if other fields are empty, like this algorithm results = Person.objects.filter(first_name__contains = "a") but if other fields are not empty, i want to filter it like this results = Person.objects.filter(first_name__contains = "a", middle_name__contains = "a", last_name__contains = "a") depending on which fields have none empty value. my first attempt was this: if first_name != "": results = Person.objects.filter(first_name__contains = first_name) if middle_name != "": results = results.filter(middle_name__contains = middle_name) if last_name != "": results = results.filter(last_name__contains = last_name) My problem here is that it filters it sequentially, so if i filter the middle_name only or last_name only, it would return me an error since results is not yet defined, could anyone help me with this? is there an algorithm that goes like this? results = Person.objects.filter(first_name__contains = first_name if first_name != "" else JUST REMOVE THIS FILTER)? because if it filters a "" it would return all your data. Thank you in advance -
Add a new datetime format to the django formats list
I use the Django formats within settings.py to keep track of all the datetime formats so they are consistent. I have various formats in my settings file, e.g: settings.py USE_L10N = False # False = Use own formats below. DATETIME_FORMAT = "d M Y, H:i" DATE_FORMAT = "j M Y" TIME_FORMAT = "H:i:s" SHORT_DATETIME_FORMAT = "Y\u2011m\u2011d H:i:s" SHORT_DATE_FORMAT = "Y\u2011m\u2011d" MONTH_DAY_FORMAT = "n M" YEAR_MONTH_FORMAT = "Y M" Then use them witth: from django.utils import formats, timnezone formats.date_format(timezone.now(), 'SHORT_DATETIME_FORMAT') A few times I have wished to add another format, e.g. to use a datetime in a filename requires different formatting (I could perform substitution in this case, but this is just an example): FILE_DATETIME_FORMAT = "Y-m-d H.i.s" With regards to above: * Note1: It does not work if placed in settings.py Closely related to this question, but this question just defines a custom format in place, which is not what I am looking for. I would like to use django's format system so there is one source of truth. QUESTION SUMMARY: How to add a new datetime format to the django formats list (and not some other work around). -
Create slug using django-uuslug
I'm trying to create slugs with django-uuslug in blog app with no success. What i'm doing wrong? My code as follows: class Post(models.Model): image = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.CharField(max_length=200, unique=True) content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) @property def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = uuslug(self.title, instance=self, max_length=200) super(Post, self).save(*args, **kwargs) -
Django doesn't load new files from static directory until server restarted
I have a Django app in production which have the functionality to save the images to the app/static/gallery/ directory from the app. then application loads those images from the directory in the template. <img src="{% static 'gallery/1.jpg' %}"> Problem here is as the application is in production & constantly saves the images under static/gallery it won't load new images until I restarted the server. I'm using http://whitenoise.evans.io/en/stable/django.html# to serve static files. → django-admin version 2.2.4 How to tackle this problem to always serve static files to load them instantly without restarting the server. -
Django Query, distinct on foreign key
Given these models class User(Model): pass class Post(Model): by = ForeignKey(User) posted_on = models.DateTimeField(auto_now=True) I want to get the latest Posts, but not all from the same User, I have something like this: posts = Post.objects.filter(public=True) \ .order_by('posted_on') \ .distinct("by") But distinct doesn't work on mysql, I'm wondering if there is another way to do it? I have seen some using values(), but values doesn't work for me because I need to do more things with the objects themselves -
Django admin group permissions not working at template level
My question is about the scope of the permissions set for a group in Django Admin. I have a few groups set up; User, Manager, and Admin. User has basic permissions, Manager has some edit/add permissions, and Admin has all permissions. I've added a user to each group and tried to test it. In my Django templates I have steps to add a Part model object. The expected result of this as a User is for this not to work, as they don't have permission. However this went through just fine and nothing stopped the User account from creating a Part. My question is why did this happen even though I set it not to happen. Do I need to add anything specific into my code for this to work? I'm not sure what code if any will help for this question so feel free to comment with requests and I will edit it in. -
Python Django logging error: Log file not created
While running Django project, I am getting the following error: Unhandled exception in thread started by Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/init.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/django/utils/log.py", line 86, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'ap_migration_log': [Errno 2] No such file or directory: '/home/dg/Desktop/dg_coco/coco-server/geographies/management/commands/log/ap_migration_log' One solution I found on stackoverflow is to create these files and then this error will not occur. But, why can't Django create log files on its own when required? Is there any config setting or command to make sure that logging file isn't created manually? -
Does any Django grandmaster know how to obtain SQL?
Does any Django grandmaster know how to obtain SQL after invoking methods on Managers? For example, Model.objects.filter(field1=x) I could probably write the SQl for it but would like to know where in Django the SQL generator is -
Should I be serving Django with gunicorn when using Google Cloud Platform's Standard Environment?
The app engine quickstart guide for django doesn't mention anything for their sample Github Repo does not have anything like gunicorn either. What is the best practice here? Also- Here is some documentation on the Python3 runtime. The quote that stands out to me and makes me wonder if I'm on the right track is: Do not include gunicorn in your requirements.txt file unless you are specifying the entrypoint. -
newsletter.send.php in django
As I'm just finishing my last part of programming of my website based on Django (& Python) I've been facing with a constant error in all applications which i have "Form.py" or "post", as you can see it in the below section: Not Found: /contact/email/newsletter.send.php [28/Jan/2020 13:15:25] "POST /contact/email/newsletter.send.php HTTP/1.1" 404 3054 I also have "Bootstrap" codes that works pretty good and I suppose this error is not occurring from the Django's programming part. This error is almost occurring at 'SEND MAIL, ADD TO CART, ADD TO WISHING LIST, SIGN IN' parts; Which means all parts that concerned with Sending-Receiving and have "Form.py", have "newsletter.send.php" error and don't work, which I almost have NO PHP Codes at all in my website programming. I also attached part of "Add to Cart" Html code below which i suppose is correct; cart.py: from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = (str(product.id)) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += … -
How to filter elements using React, Graphql and Apollo with es6
I have a React project with a GraphQL using Apollo client. I am trying to figure out how to change the query result based on search text. I implemented query search in backend and its working perfectly. But I dont know how to set up filter in React using that same query. Despite there is tutotial on how to filter on https://www.howtographql.com/react-apollo/7-filtering-searching-the-list-of-links/, it doesnt use ES6 and I literaly dont know how to do it. Im stuck on this filter around 10 days. I will show you my code. App.js import React from 'react'; import HeroesDota from './components/HeroesDota'; import Search from './components/HeroSearch' import { ApolloProvider } from '@apollo/react-hooks'; import { ApolloClient } from "apollo-client"; import { InMemoryCache } from "apollo-cache-inmemory"; import { HttpLink } from "apollo-link-http"; const cache = new InMemoryCache(); const link = new HttpLink({ uri: "http://localhost:8000/graphql/" }); const client = new ApolloClient({ cache, link }); const App = () => { return ( <ApolloProvider client={client}> <Search /> <HeroesDota /> </ApolloProvider> )}; export default App; HeroesDota.js (compoenent) import React from 'react' import gql from "graphql-tag"; import { useQuery } from '@apollo/react-hooks'; import '../index.css' import styled from 'styled-components'; const Images = styled.img` margin:0; border: 3px solid #288eea; display: inline; width: … -
javascript setInterval start when click on buttun
I am trying to start setInterval when user presses a button. function clickButton() { document.querySelector('#run_py').click(); } setInterval(clickButton, 60000); I can I do this without jquery? -
Delete Specific Post from Front-end using ajax in Django (Class Based View)
I have lot of posts generated using loop in django, and want to delete specific post (like Facebook delete works). I am able to get id of post using jquery but i am not sure what I am doing wrong to delete post. I have also implemented delete function in class based view. Delete Post Button existing-dashboard.html {% for i in all_posts %} ... ///rest of the code <span class="username"><a href="#">{{ i.first_name }} {{i.surname}}</a> <span class="more" id="more-icon">{{i.post_id}} <div class="more-menu" style="margin-top: 30px;"> <span class="delete" id="{{i.post_id}}">delete</span> </div> </span> ... /// rest of the code </span> {% endfor%} Ajax $('.delete').on('click', function(){ var post_id = $(this).attr('id'); alert(post_id) $.ajax({ url: 'http://127.0.0.1:8000/existing-delete/' + post_id +'/', type: 'DELETE', data: {}, contentType: 'application/json', dataType: 'text', error: function(result){ alert(result) }, success: function(result){ alert(result) } }) }) views.py class ExistingStudentDashboard(TemplateView): .../// rest of the code def delete(self, request, pk, format=None): post1 = Existing_student_posts.objects.filter(id = pk).first() post2 = Future_student_posts.objects.filter(id = pk).first() post3 = Teacher_posts.objects.filter(id = pk).first() post4 = Employee_posts.objects.filter(id = pk).first() if post1: post1.delete() elif post2: post2.delete() elif post3: post3.delete() else: post4.delete() get_context_data() urls.py path('existing-delete/,<int:pk>', views.ExistingStudentDashboard.as_view(), name = 'existing-delete'), Getting Error in Console like bellow Not Found: /existing-delete/61/ Browser Console Error Browser Console Error What I am doing wrong to delete … -
Validating a formset using data from another form
I'm having to do some validation across both a form and formset. The £££ amount in the form must equal the sum of the amounts in the formset. After a lot of Googling I found a solution where I add a custom init to the baseformset as follows: class BaseSplitPaymentLineItemFormSet(BaseFormSet): def __init__(self, cr=None, *args, **kwargs): self._cr = cr super().__init__(*args, **kwargs) def clean(self): if any(self.errors): return sum_dr = 0 for form in self.forms: sum_dr += form.cleaned_data.get('dr') if sum_dr != float(self._cr): raise forms.ValidationError('The amount entered needs to equal the sum of the split payments.') I then pass the amount value from the form when the formset is instantiated, so that the value can be used in the formset validation: lineitem_formset = LineItemFormSet(form.data['amount'], request.POST) This worked great for the create_new view which uses formset_factory(). This morning I wrote the update view using inline_formsetfactory(), but I now get an error: __init__() got an unexpected keyword argument 'instance' I only have a basic understanding of how the custom init works, so I can't find a solution to this error. Forms.py: class SplitPaymentForm(forms.Form): date = forms.DateField(widget=DateTypeInput()) account = GroupedModelChoiceField(queryset=Ledger.objects.filter(coa_sub_group__type='a').order_by('coa_sub_group__name','name'), choices_groupby = 'coa_sub_group') store = forms.CharField(required=True) amount = forms.DecimalField(decimal_places=2) class SplitPaymentLineItemForm(ModelForm): ledger = GroupedModelChoiceField(queryset=Ledger.objects.all().order_by('coa_sub_group__name', 'name'), choices_groupby = … -
Django: problem with django-tempus-dominus datepicker
I try to use django-tempus-dominus for my DateFields (https://pypi.org/project/django-tempus-dominus/) but it doesn't works 3 problems: can add options, attr, etc. -> init() got an unexpected keyword argument 'options' django initial date doesn't works when I select a date with the date picker, date is display with the french format (dd/mm/yyy) instead of default format (yyyy-mm-dd) so that records can not be registered what is wrong? settings.py TEMPUS_DOMINUS_LOCALIZE = False (to unforce default format date) forms.py from django import forms from .models import Entree import datetime import time from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError from parameters.models import Thesaurus, Pays, Site from tempus_dominus.widgets import DatePicker, TimePicker, DateTimePicker class EditForm(forms.ModelForm): # surcharge méthode constructeur (__init__) pour avoir accès aux variables de sessions # https://stackoverflow.com/questions/3778148/django-form-validation-including-the-use-of-session-data def __init__(self, request, *args, **kwargs): super(EditForm, self).__init__(*args, **kwargs) self.request = request self.language = request.session.get('language') if self.language == 'en': PAYS = Pays.options_list_eng() SITE_CONCERNE = Site.options_list_code_eng() SITE_PROVENANCE = Site.options_list_abreviation_eng() else: PAYS = Pays.options_list_eng() SITE_CONCERNE = Site.options_list_code_fra() SITE_PROVENANCE = Site.options_list_abreviation_eng() self.fields["asp_ent_loc"] = forms.ChoiceField(label = _("Site concerned by the operation"), widget=forms.Select, choices=SITE_CONCERNE) self.fields["med_num"] = forms.CharField(label = _("Trial bacth number"), required=True) self.fields["asp_ent_dat"] = forms.DateField( label = _("Entry date"), required = True, widget=DatePicker(), # https://pypi.org/project/django-tempus-dominus/ initial = datetime.datetime.now, ) self.fields["asp_ent_pro_pay"] = … -
Attendance for Employees Management System in Django?
I am working on Employee Management System in Django. I want to add attendance module to this project. I have made Employee model by extending Django User Model and added some new properties like DOB , Department etc. Please give a rough idea on what should I do in order to achieve this. I am still learning Django so your help will highly appreciated. -
How to safe delete row from table with composite key in Django?
I have a intermediate table in which there are two columns that make up the primary key. When I try to delete one row, all rows with this primary key deleted. How i can do normal deleting? class ServiceKey(models.Model): service = models.ForeignKey( Service, on_delete=models.PROTECT, related_name='service', null=False, ) key = models.ForeignKey( ApiKey, on_delete=models.DO_NOTHING, related_name='apikey', null=False, primary_key=True ) class Meta: unique_together = (('service', 'key'),) -
Django error: save() got an unexpected keyword argument 'toppings'
On the admin UI, after fillings the fields and pressing the 'save' button, I get this error Can anyone tell me what is the issue? From what I have read, this issue is often caused by not putting this line of code super(Pizza, self).save(*args, **kwargs), yet I still get this error and am unable to understand why FYI: I want to make each Pizza to have a default Topping of Cheese, and this for all Pizza and it should not be able to remove it class Topping(models.Model): name = models.CharField(max_length=64) def __str__(self): return(f"{self.name}") class Pizza(models.Model): PIZZA_SIZES = ( ('S', 'Small'), ('L', 'Large'), ) pizza_type = models.CharField(max_length=64) pizza_size = models.CharField(max_length=1, choices=PIZZA_SIZES) qty_toppings = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)], default=0) toppings = models.ManyToManyField(Topping) price = models.IntegerField(help_text="Price in $") def __str__(self): return f"Size: {self.get_pizza_size_display()}, Type: {self.pizza_type}, Number of Toppings: {self.qty_toppi\ ngs}, Price: {self.price}, Toppings: {self.toppings.in_bulk()}" def save(self, *args, **kwargs): # if 'toppings' not in kwargs: # kwargs.setdefault('force_insert', True) # kwargs.setdefault('force_update', True) kwargs.setdefault('toppings', Topping.objects.get(name='Cheese')) super(Pizza, self).save(*args, **kwargs) -
Previous cached data prevents update in django
I'm working with django session using cached session configuration. My session object holds a value which when updated doesn't get reflected on my webpage until i use browser's hard refresh. any help or suggestion will be greatly appreciated ( actually my first time working with session and cache directly ) A Quick Analogy: Before update count = 0 and after update count = 1 count value is saved on django's session object request.session['counter'] = count The problem instead of having 1 displayed on my template (HTML), i get 0 instead. This is true unless i do a hard refresh on my browser ( Cntrl + r ) which will only update current page, but every other pages will hold previous value of count which is 0 MY CODE View which handles update def increment_quantity(request): quantity = int(request.POST.get('quantity')) item_id = int(request.POST.get('item_id')) item = get_object_or_404(Product, id=item_id) if quantity < 1: quantity = 1 item.quantity = quantity item.save() if request.session.get('product_present', False): # if a product is present product = Product.objects.get(pk=int(request.session['product_id'])) request.session['product_count'] = product.get_total_item() products = get_all_products(request) return redirect('product:product_list') Stack Overflow's solution that i've tried link one link two What i've tried personally I've tried using middleware that get called for each request and … -
How to censor specific fields based on condition using django QuerySet API
Using Django we have situation where we have a model Case which can be set to being a medical case or not (through a BooleanField). Now, we also have a system to check if a certain employee (User subclass) is authorized to see sensitive data when a case is labeled as being medical (containing medical sensitive data). I am able to annotate a new field to each instance, a BooleanField letting us know if the requesting employee is authorized to see medical data on the specific Case instance or not. Ideally, I would like to have the database sensor out specific fields (field customer for example), when the requesting employee is not authorized to see medical data for that case. I imagine this can be done with an annotate method, and a combination of from django.db.models.Case and from django.db.models.When. But, what we would also like is that the resulting QuerySet keeps the same field names on the different model instances. We don't want to change the field name of customer to another name. We have actually come up with a solution, using .values first, and then the .annotate for each field we want to potentially censor out (see code below). … -
Pythonanywhere - ConnectionRefusedError: [Errno 111]
Here I have a model called User. It has 2 fields "Name" and "Phone". I am trying to authenticate with an OTP. Actually the code works fine on the local server. For this reason, I hosted the project on Pythonanywhere, but now it's getting an error on the server ConnectionRefusedError: [Errno 111] Connection refused Essentials Below is the code for the OTP message to send def generate_otp(user, name, phone): otp = users.models.User.objects.make_random_password(length=4, allowed_chars='123456789') if not users.models.VerifyToken.objects.filter(user=user).exists(): users.models.VerifyToken.objects.create(user=user, otp=otp, name=name, phone=phone) send_verification_message(phone, otp) else: token = users.models.VerifyToken.objects.get(user=user) token.otp = otp token.name = name token.phone = phone send_verification_message(phone, otp) token.save() return otp def send_verification_message(phone, otp): phone = phone[3:14] conn = http.client.HTTPSConnection("api.msg91.com") payload = "{ \"sender\": \"BMyDay\", \"route\": \"4\", \"country\": \"91\", \"sms\": [ { \"message\": \"" + "Your verification code is " + otp + ".\", \"to\": [ \"" + phone + "\" ] } ] }" print(payload) headers = { 'authkey': "xxxxxxxxxxxxxxxxxxx", 'content-type': "application/json" } conn.request("POST", "/api/v2/sendsms", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) return True View This is my view class AuthAPIView(APIView): queryset = User.objects.all() lookup_field = "phone" permission_classes = [AllowAny] # Get OTP def put(self, request): name = request.data.get('name') phone = request.data.get('phone') if name and phone and phonenumbers.is_valid_number( …