Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) … -
Group Concat in Django
I am having a model class Project(models.Model): project = models.CharField(max_length=255, blank=True, null= True) user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() start_date = models.DateField() THis is my query for fetching the data qs = Project.objects.values('project').annotate( total_hours=Sum((F('end_time') - F('start_time'))), start_date =F('start_date'), ).distinct() for i in qs: print(i) Now what I am getting is {'project': '1', 'total_hours': Decimal('2.0000'), 'start_date': datetime.date(2020, 8, 1)} {'project': '3', 'total_hours': Decimal('1.0000'), 'start_date': datetime.date(2020, 8, 1)} {'project': '1', 'total_hours': Decimal('1.0000'), 'start_date': datetime.date(2020, 8, 2)} Here if project 1 coming twise in to diffrent dates.... How to elimintate second one add as a single object So I am trying to use GROUP_CONCAT https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat THis is the code class GROUP_CONCAT(Func): function = 'GROUP_CONCAT' template = '%(function)s(%(expressions)s)' output_field = DateField() But I am not sure How can I use it with Django ORM Query -
Django Aggregation: Summation of Multiplication of two fields with ForienKey
I have two model as below class Product(models.Model): title = models.CharField(max_length=128) slug = models.SlugField() price = models.DecimalField(default=0.0,decimal_places=2,max_digits=15,validators=[MinValueValidator(Decimal('0.00'))]) def __str__(self): return str(self.title) class OrderItem(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.product.title}" def subtotal(self): return self.quantity * self.product.price I want the total of all subtotal using aggregate but total1 = OrderItem.objects.all().aggregate(total=Sum(F('product.price') * F('quantity')))['total'] returns Cannot resolve keyword 'product.price' into field. Choices are: id, order, product, product_id, quantity and total2 = OrderItem.objects.all().aggregate(total=Sum(F('subtotal') * F('quantity')))['total'] returns Cannot resolve keyword 'subtotal' into field. Choices are: id, order, product, product_id, quantity, user_session error -
Browser error during django + SSL connection with local server
I have a problem during adding facebook login button to my website at localhost. I've already add mysite.com to hosts file and installed django-extensions, werkzeug, pyOpenSSL. By running command python manage.py runserver_plus --cert-file cert.crt my own-made sertificate was created. I imported this certificate to Trusted Chrome sertificates but safe connection doesn't establish. When i pass https://example.com:8000/account/login/ I hit an error NET::ERR_CERT_COMMON_NAME_INVALID, Failed to confirm that this is the server example.com. Its safety certificate refers to *. The server may be configured incorrectly or someone is trying to intercept your data. Please help me to solve this. -
Media File folder issue on python any where Server
I'm facing a weird issue, my media folder get created outside of the project directory on pythonanywhere, there is no issue on a local server, I uploaded many sites on pythonanywhere but this issue I faced the first time. If you help me to resolve this I shall be thankful to you. Note: My static files are run fine only issues with the media root folder python anywhere folder. Setting file -
For blog post i used tags by many_to_many filed. Now i try to use Django_Taggit for tag field, but i face some error while makemigration
Old MODELS.py when use tags by many_to_many fields class Tag(models.Model): tag_name = models.CharField(max_length=64, unique=True) tag_slug = models.SlugField(max_length=64, unique=True) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) def __str__(self): return self.tag_name def get_absolute_url(self): return reverse("news:tag-detail", kwargs={"slug": str(self.tag_slug)}) class News(models.Model): title = models.CharField(max_length=192, unique=True) slug = models.SlugField(max_length=192, unique=True) cover_photo = models.ImageField(upload_to='news', blank=True, null=True) summary = models.CharField(max_length=280) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) # tags = models.ManyToManyField(Tag, blank=True, related_name='post_tag') class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse("news:post", kwargs={"slug": str(self.slug)}) current models.py After install Django_Taggit i remove tags model and rewrite tags line class News(models.Model): title = models.CharField(max_length=192, unique=True) slug = models.SlugField(max_length=192, unique=True) cover_photo = models.ImageField(upload_to='news', blank=True, null=True) summary = models.CharField(max_length=280) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) tags = TaggableManager() class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse("news:post", kwargs={"slug": str(self.slug)}) Also i remove tags from view.py and urls path and update html but when i try to makemigrate i face this error python manage.py makemigrations news SystemCheckError: System check identified some issues: ERRORS: news.News.tags: (fields.E300) Field defines a relation with … -
How do I set value for foreign key field?
I want to set the value for this CustomerReg in picture above to request.user.username I am able to manually select it, what I want is after login it gets directly assigned to person who has logged in to submit this form. views.py(multi_form view and register view) I cannot automatically assign CustomerReg field in Customer model. def registerPage(request): if request.user.is_authenticated: return redirect('form') else: form=CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if(form.is_valid()): form.save() user=form.cleaned_data['username'] messages.success(request, 'Account created for '+ user) return redirect('login') def multi_form(request): form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): form.save() print(request.user.id) messages.success(request, "Your Response has been recorded") context={'form':form} return render(request, 'customer/index.html', context) models.py(Customer and CustomerReg model) Customer model has customerReg field as foreign key. class CustomerReg(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) email=models.EmailField(max_length=254) def create_profile(sender, **kwargs): if kwargs['created']: user_profile=CustomerReg.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) class Customer(models.Model): id=models.AutoField(primary_key=True, default=None) customerReg=models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) first_name=models.CharField(max_length=200, blank=False, default=None) last_name=models.CharField(max_length=200, blank=False, default=None) -
Use Email instead of Username to authenticate user
I know this answer have a lot of answers and many different ways to do that , But As of today in Django 3 I want to know which one is best and reliable way to use only email for authentication . -
python-socketio websocket emit to particular client in Socket.IO an ionic application
In my project I am using a Django application that acts as a SocketIO server to the Ionic mobile application which uses Socket.io to connect to the server as a client. My django application has another socket connection and it acts as a client to another micro service in python which uses python-socketio to create a websocket server. When I send a request from the Ionic application, it reaches the Django server which sends the request to the client via Django signals and then the request is sent to the micro services and the response from them are to be sent to the same Ionic application via Django. I was able to do it successfully when the Ionic application is only one. When there are multiple Ionic clients and when the data is different for them both, this does not make an effect. Both the clients receive the same data. My requirement forces me to have the communication through the Django server. Can anyone help me with this? Microservice (python-socketio) <--> Django (python-socketio) <--> Ionic application (socket.io) The communication is by websockets by eventlet. -
Django ORM in one query get two result
I have a query and i am trying to count total open Quote and total bids of open quote. thse are my models class Quote(models.Model): STATUS= ( ('OPEN', "Open"), ('CLOSED', "Closed"), ) status= models.CharField(max_length=14, choices = STATUS, default='OPEN') class Bid(models.Model): text = models.TextField(max_length=1000) quote = models.ForeignKey(Quote, on_delete = models.DO_NOTHING, related_name='bids') and thise is my query in django rest frameowrk for a json response def get(self, request): quote = Quote.objects.filter(status='OPEN').count() bids = Bid.objects.filter( quote__status='OPEN' ).count() return Response({ 'quotes_count': quote, 'bids_count': bids, }) Everything is working great ! but i don't like that this, coz, I think the two queries is completely worst practice, coz, i think it's possible to get same result in a single query. Can anyone please help me to optimize this query? I mean, i want to query in one veriable to get two dffierent result (Total Open Quote and Total bids of actual open quote) -
Lookups that span relationship -
I am a Django newbie so I think this is too basic to google! Thanks so much for your help! I want to do a lookup that spans three classes. In this case, I want to find all the PartListing that match the specific_part in the ListItem. I have these models: class SpecificPart(BaseModel): class PartListing(BaseModel): specific_part = models.ForeignKey( SpecificPart, on_delete=models.CASCADE, blank=True, null=True, related_name="part_listing") class ListItem(BaseModel): specific_part = models.ForeignKey(SpecificPart, on_delete=models.CASCADE, related_name="listitem") I'm trying to put the lookup under the ListItem class like this: def item_match(self): part = self.specific_part return PartListings.filter(specific_part__specific_part=part) I am getting an error that PartListing is not defined but I also suspect that I'm referencing the foreign keys incorrectly. -
Django Admin Related Problems
I want to customize the Django Admin Panel means creating my own admin Panel from scratch. Creating groups permission from scratch. Also, modify Django username Field to Email Field. Is there anyone who can do all stuff in his/her project. Please send me the project document for educational purposes. In my college, I want to show projects on these related topics. -
Confusion in form.save() in two different models
I am having problems in displaying the page due to models. I honestly don't know what the problem is and every solution I see here is beyond me, since I am only beginning to learn Django. Here's the summary: I have created two forms from two models(which are interrelated) and rendering the data from those forms in a single page. The data displays fine on the dashboard panel and the submission does save it to the database. However, whenever I try and load the pages containing same data (display pages like home for customers)I am hit with: get() returned more than one Order -- it returned 2! The code in forms.py: from django.forms import ModelForm from shop.models import * class OrderForm(ModelForm): class Meta: model = Order fields = ('customer',) class OrderItemForm(ModelForm): class Meta: model = OrderItem fields = ('item', 'status',) views.py def createOrder(request): form_order = OrderForm() form_orderitem = OrderItemForm() if request.method == 'POST': # print('Printing POST', request.POST) form_order = OrderForm(request.POST) form_orderitem = OrderItemForm(request.POST) if form_order.is_valid() and form_orderitem.is_valid(): form_order.save() form_orderitem.save() return redirect('/dashboard') context = {'form_order': form_order, 'form_orderitem': form_orderitem} return render(request, 'dashboard/order_form.html', context) -
Generic UpdateView isn't working with slug
I'm pretty new to django.I am trying to update a post with generic UpdateView. But the post isn't updating after filling up the form.Im accessing the update view through slug url. My model: class Post(models.Model): title = models.CharField(max_length=60) post_body = models.TextField() time_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) slug = models.SlugField(null=False,unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('postdetail', kwargs={'slug': self.slug}) def save(self,*args,**kwargs): if not self.slug: author_id = str(self.author.id) self.slug = slugify(self.title +'-'+author_id) return super().save(*args, **kwargs) My view: class postupdate(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model = Post fields = ['title','post_body'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False My url: path('post/<slug:slug>/updatepost/', postupdate.as_view(),name = 'updatepost'),