Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe Error: As per Indian regulations, export transactions require Customer's address, but i am selling digital prints
I am building an app with React and DRF to sell digital prints (Jpeg, png, psd). I am using stripe as payment gateway and I am getting this error. If I am selling digital product than there is no need to ask for Customer's address. I am not exporting anything. The idea is to charge customer for a print than provide a downloadable link to download purchased files Is there any way to charge customers without an address using stripe ? -
Where to hide password to sql server while deploying django app into Azure from github?
I'm trying to deploy my app on Azure, but I don't know where may I hide a password to SQL server. I usually hide it with decouple module or in environment, but while deploying azure doesn't have access to those. And without this password I get error while running oryx build: raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: PASSWORD not found. Declare it as envvar or define a default value. Does anyone has an idea how to do so? -
Wagtail ValidationError on publish (page revision instance does not exist)
We are facing an issue with Wagtail. Whenever one makes an edit to a page and selects "Publish", they are faced with a ValidationError with the message {'live_revision': ['page revision instance with id 74 does not exist.']} (see screenshot). This only seems to occur when the page is in "Draft" status, though I cannot confirm that this always holds. When I view the page revisions, I can confirm that a revision with ID 74 does indeed not exist. My question is, how might this have occurred, how can we fix it so that we are able to publish the page currently, and what can we do to prevent this from occurring in future? Any assistance is greatly appreciated. I am aware of a similar question on StackOverflow that has already received an answer (Wagtail raises ValidationError on page update), however this answer does not help in our situation as we are not using ParentalKey in any of our models. -
How to get objects with certain foreignkey relationships in ORM?
Assume we have a product model: class Product(models.Model): name = models.Charfield() And a property model where possible properties are defined (like "price", "color", "weight"...): class Property(models.Model): name = models.CharField() And we keep product properties in a separate model: class ProductProperty(models.Model): property = models.ForeignKey(Property) product = models.ForeignKey(Product) value = models.Charfield() I want to get product objects which have certain properties. For instance, I want to get objects only if "price" and "color" is defined for them in ProductPropery table. I obtain the required properties as objects, but I could not solve how can I get products that have all of the given properties. To rephrase, I'm looking for something like this: properties = Property.objects.filter(Q(name__contains="Price") | Q(name__contains="Color")) #this could return one or multiple property objects products = properties.productproperty_set.product_set # imaginary line I made up to show what I want to get I could only think of looping through properties and an inside loop for related ProductProperties to get their products to create multiple lists, and then create a list that's made of common elements (products that are included in each list). -
Display the latest news separately from other
I want to display the latest news on one page separately and all the rest below, but I don't know how this can be done. views.py class PostsView(ListView): model = Post queryset = Post.objects.all().order_by('-date') template_name = 'post/posts.html' urls.py urlpatterns = [ path('', views.PostsView.as_view()), path('<int:pk>', views.PostView.as_view()), path('add/', views.PostFormView.as_view(), name='add'), ] -
how can I add a url for my template in django python?
i use a template im my django homepage.(http://127.0.0.1:8000/) I linked statics files in static folder and formed like {% static .....} when i path it in urls in the main page it work correctly. but when I give it an slug like 'p/' it doesn't work. because it search for statics in p folder: "GET /p/static/post/js/scripts.js HTTP/1.1" 404 2598" my app name is "post" . please help? -
django - edit_entry() missing 1 required positional argument: 'entry'
Helllo, I am getting this error when trying to retrieve the content of util.get_entry(entry). Where shoud I correct this " missing positional argument? Is possible I am getting this error because of my django version? Because it seems to work to a colleague. I tried a code a code that was confirmed to be working to test. Any hint? enter code hereef edit_entry(request, entry): form = EditEntryForm(request.POST) if request.method == "POST": if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title,content) return render (request, "encyclopedia/edit.html",{ "content":content, "title":title }) if request.method =="GET": content = util.get_entry(entry) return render(request, "encyclopedia/edit.html", { form: EditEntryForm(entry) }) -
Can you have a function call inside a django form that does a database query before migrations have been fully migrated
I have the following form class RegionForm(forms.Form): REGIONS = get_regions() region = forms.ChoiceField( label='Region', choices=REGIONS) Which I’m importing in my views.py as from forms import RegionForm These views are then imported in the urls.py for use as views from reports.views import ReportView, data_export However, this import is causing the method here REGIONS = get_regions() to be executed. The get_regions function does database query which is causing query exception if the migrations haven’t been applied yet which is usually anytime I’m trying to run the app with a clean database. My question therefore is; Is there a way to prevent the method from being executed immediately after being imported? -
Comparing Datetime and datetimefield django
I am Trying to compare the datetimefield stored in my item to a datetime.date object. Here is the code in views.py where i create instances of datetime.date objects and select the datetimefield of the item from the database and try to compare them. def Comapare(request,pk): Item = item.objects.get(id=pk) date1 = request.GET.get('date1') date2 = request.GET.get('date2') if date1 and date2: if ',' in date1: date1 = list(date1.split(',')) else: date1 = list(date1.split(' ')) if ',' in date2: date2 = list(date2.split(',')) else: date2 = list(date2.split(' ')) date1 = datetime.date(int(date1[0]), int(date1[1]), int(date1[2])) date2 = datetime.date(int(date2[0]), int(date2[1]), int(date2[2])) was_date1_before = date1 < date2 if not date1 < date2: date1, date2 = date2, date1 if date1 < item.date_created: date1 = '' context = { 'date1':date1, 'date2':date2, 'was_date1_before': was_date1_before, 'item': Item, } else: context = {} return render(request, 'Inventory_Management/getDate.html', context) when i am trying to compare them in the above example i get the following error : '<' not supported between instances of 'datetime.date' and 'DeferredAttribute' i tried to search on the internet but didn't really find anything to help. I Get the date from the html file which is the following one {% extends 'Inventory_Management/layout.html' %} {% block body %} <form> <div class="form-group"> <label for="date1">Date 1</label> <input … -
Cannot assign requested address in Django on docker-compose
Someone know how can change the request url in Django? Deacription I'm developing Django app on docker. I'm using 「dj-rest-auth」 for auth system. When I try to registration that API return 500. Error is 「[Errno 99] Cannot assign requested address」. The stack trace wrote like that Request URL: http://containerName/rest-auth/registration/. So Django try to return request url with docker container name. I know that is nomall do Djnago. But I expect change container name to 「localhost」or something. I think it is docker issue... But I don't clear that problem. So if someone know how that solve that , please let me know that. Thanks! Full StackTrace Environment: Request Method: POST Request URL: http://containerName/rest-auth/registration/ Django Version: 3.0.7 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news.apps.NewsConfig', 'rest.apps.RestConfig', 'users.apps.UsersConfig', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'dj_rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.sites', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, … -
Django ValueError: Cannot query "": Must be "User" instance
Hello I am getting a ValueError: Cannot query "": Must be "User" instance. error when creating a user using django-rest-auth. I have created a custom account model in order to do this. serializer.py class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['email', 'username', 'password'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = Account( email=self.validated_data['email'], username=self.validated_data['username'], ) password = self.validated_data['password'] account.set_password(password) account.save() return account urls,py app_name = 'account' urlpatterns = [ path('register/', registration_view, name="register"), path('login/', AuthToken.as_view(), name="login"), path('password_reset/', AuthToken.as_view(), name="login"), ] views.py @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'successfully registered new user.' data['pk'] = account.pk data['email'] = account.email data['username'] = account.username token = Token.objects.get(user=account).key data['token'] = token else: data = serializer.errors return Response(data) models.py class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username … -
Crontab format comparision
I want to schedule a cron every Monday at 4:30 in my Django project using django_crontab. I have two formats below. Please suggest if both are same or i should use MON instead of 1 ('30 4 * * MON', 'drc.refresh.test', ['request']) or ('30 4 * * 1', 'drc.refresh.test', ['request']) -
Authorization error while implementing google auhentication in django app
In my django project I have added google authentication API for user login and have deployed that project in heroku server[https://artgreeh.herokuapp.com]. I tried login through Google it worked with no issue in some machine but it's showing error in other machine. error image. In the google I have given redirect url-"https://artgreeh.herokuapp.com/accounts/google/login/callback/". If something is wrong with redirect url then it should not work in any device but it's working in some device. -
Django initializing database content for each client
I am currently building a web application in Django that will be deployed in each clients internal network (next year up to 10 clients probably). Each client's installation should be initialized by our developers with some initial data. This data spans over multiple tables and the entities are connected to each other (currently MySQL). There are different default configurations (default datasets) and we might have to adapt a few things for each client individually furthermore (but we will be able to do this via the default admin interface of django). Do you have any recommendations on how to set this up properly? At the moment we have just created an initial python script that uses a json file, parses it and then manually iterates over it, adding the entities to the database if that specific table is empty. This seems quite hacky. Is there any initialization framework or something similar we could use to initialize some starting data? Just creating an initial SQL file seems hacky, too, as it would completetly break at the slightest change of the datastructure or naming. Any hint or recommendation is valuable. Please don't feel compelled to write fully functional code :) -
Issue importing model class into a populating script
I am quite new to Django so bare with me, I have read a few Stack Overflow answers on similar but they seem to be much more complicated than what I am trying to do. Any help would be appreciated. I have followed a tutorial on Udemy which built a website with some models, and then populated them with data using a python script. From this course; https://www.udemy.com/course/python-and-django-full-stack-web-developer-bootcamp I am trying to do the same and have followed the steps as analogously as I can. I have; declared the models in app_name/models.py imported them into app_name/admin.py and registered them included app_name in INSTALLED_APPS in settings.py Currently when I log onto the admin of my server I can see the models and add to them. What I cannot seem to do is import the models into my populate.py script which is located in the top level folder. The script is as follows; import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') import django django.setup() import pandas as pd import glob from smart_plug.models import Model_Name I am getting the following error; RuntimeError: Model class smart_plug.models.Topic doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I am not sure whether I have posted all of … -
Account didn't active after I confirmed my email in django
I wrote some code in django about registration with a verification email and the email has sent to me and I confirmed it but my acc didn't activate. I don't know if the problem is with my activate function or what here is the error I get : and this is my activate function: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and acc_activation.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('home') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') and my activation_email.html code : {% autoescape off %} Hi {{ user.username }}, pleace click here to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} -
How to save session data without overloading database
I have a flashcard app database that will record user progress as they quiz themselves. Users will be answering questions with yes/no/maybe at a rate of about 5-10 seconds per response. The problem is that some users will continue this question/answer session for long periods of time and I don't want them to lose their progress if something distracts them and they close the app halfway through the study session. One one hand, I could have each question send a request to the database to update user progress every time a user answers a question. On the other hand, I could have all of the progress saved somewhere on the client side (cookies?) and then update the database once at the end of the session. My fear is that the first option is not scalable if thousands of users use the site simultaneously. However, with the second option, I'm sure that progress will be lost if a user closes the session unexpectedly. What is the best way to continuously save user progress without overloading the database? -
Python Flask - Django API check if previous call was made [closed]
Did somebody build something similar to this like open library: Check if api call has been made like a step by step process for example I make get http request to /api/1 > returns json data then I make get http request to /api/2 > returns json data, but if http request to /api/2 is made without /api/1 it should return bad request call -
Can't Send Email in Django-Crontab
I am using django-crontab for cron tasks in Django. I am running locally and want to use this crontab to send myself an email every minute. Here is my crontab: def my_cron_job(): # Start test f = open('/Users/myuser/Desktop/start.txt', 'w') f.close() # Send email send_email(to='me@gmail.com') # End test fr = open('/Users/myuser/Desktop/end.txt', 'w') fr.close() The problem is as follows: the file, start.txt is created. However the email is not sent and the end.txt file is not created. I am 100% sure that it is not a problem with my send_email function. Why is this happening? Thanks! -
How to measure django app coverage with codecov during end to end tests
To simplify the question I am trying to collect code coverage from a django rest service when my UI end to end test suite is executed. I've done this with node in the past where you instrument the code before running the node app, and I was hoping you could accomplish the same with codecov on a python django app. I tried looking for recipes and looking at docs and I haven't had much luck. -
Why am I getting name 'shared_task' is not defined error with Celery
I am learning celery by following this tutorial. I created the tasks as he did and tried running the code. But I get the following error NameError: name 'shared_task' is not defined This is my code import requests from bs4 import BeautifulSoup import json from datetime import datetime import lxml @shared_task def scrape(): try: ... This code is working for him but I get the above mentioned error. Not sure what I am doing wrong. Please help me Thanks in advance -
Django Manager isn't accessible via CustomerPurchaseOrderDetail instances
I have this model CustomerPurchaseOrderDetail, Product, Customer, I just want that if the same productID and same CustomerID exists in the CustomerPurchaseOrderDetail model, the quantity will add 1 if the same productID and same CustomerID exists in the CustomerPurchaseOrderDetail. This is my views.py userID = request.POST.get("userID") client = Customer(id=userID) vegetables_id = request.POST.get("id") quantity = request.POST.get("quantity") v = Product(id=vegetables_id) price = request.POST.get("price") discount = request.POST.get("discount_price") insert = CustomerPurchaseOrderDetail.objects.get_or_create( profile=client, product = v, quantity=quantity, unitprice=price, discounted_amount = discount, discounted_unitprice = discount, ) order_qs = CustomerPurchaseOrderDetail.objects.filter(profile = client, product = v) if order_qs.exists(): order = order_qs[0] if order.objects.filter(profile = client).exists(): insert.quantity += 1 insert.save() else: order.quantity.add(insert) else: order = CustomerPurchaseOrderDetail.objects.create( profile=client, product=v, unitprice=price, quantity=1, discounted_amount=discount, discounted_unitprice=discount, ) order.save() this is my models.py class CustomerPurchaseOrderDetail(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Product") quantity = models.FloatField(max_length=500, null=True, blank=True, default=1) class Product(models.Model): product = models.CharField(max_length=500) class Customer(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) firstname = models.CharField(max_length=500, blank=True) lastname = models.CharField(max_length=500, blank=True) contactNumber = models.CharField(max_length=500, blank=True) email = models.CharField(max_length=500, blank=True) this is my full traceback Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = … -
Ajax requests not going through, Elastic Beanstalk with classic load balancer
I have an issue with AJAX requests not going through on my site. The issue started after I made an application load balancer on the EC2 instance, with a redirect on port 80 to the HTTPS version. I noticed today that my elastic beanstalk environment has a classic load balancer in the configuration. Could this be the source of the problem? The rest of the site loads up just fine, but when it comes to the AJAX, those requests don't seem to be going through. Could making a new elastic beanstalk environment with an application load balancer solve this issue? Or do you have any other suggestions what may be causing this? Environment is Python 3.6/Amazon linux, I am running a django app on it. I'm not getting any more bad requests after putting all network interfaces on my allowed_hosts. -
Handle Atomic transactions in Django for making an rest api call to create something on 3rd party app, and doing corresponding updates on own database
I am working on a django project. One requirement is to call a 3rd party Zoho books api to create a bill, and then link the bill id to one of our dev database table. And this should be done atomically. So if bill is created successfully inside zoho books, but somehow linking could not be done. It should rollback the bill creation as well. My doubt is this really possible ? If not, should I just create an implementation to create the zoho bill, add the link for the bill id in the database if bill created successfully, and if link creation is unsuccessful, just delete the zoho bill. Is this approach correct ? -
TypeError: metaclass conflict (Django)
I'm building a Django API and facing this error class Customer(User, PermissionsMixin): TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I have two apps in my Django Project : Retailer and Customer. I have inherited Django's inbuilt User Model for the customer model and retailer model. Here is how retailer : models.py class User(AbstractBaseUser, PermissionsMixin): username=None email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField( 'staff status', default=False, help_text='Designates whether the user can log into this admin site.', ) is_active = models.BooleanField( 'active', default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', ) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Retailer(User, PermissionsMixin): ret_name = models.CharField(max_length=255) phone_number = models.CharField(max_length=10) verification_status = models.BooleanField(default=False) document_status = models.BooleanField(default=False) created_at = models.DateField(default=timezone.now) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['ret_name', 'phone_number',] objects = RetailerManager() def __str__(self): return self.ret_name Now I'm inheriting this User model in the customer app. customer : models.py class Customer(User, PermissionsMixin): cust_name = models.CharField(max_length=255, null=False,) phone_number = models.CharField( max_length=10, null=False) address = models.TextField(max_length=255, null=False) pin_code = models.CharField(max_length=6, null=False) anniversary_date = models.DateField(blank=True, null=True) …