Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return manytomany field by nested relationship, and update by id
I have two models MusicandMusicList(manytomanyfield), and I use ViewSet to generate api. I expected that it returns Music's detail(include music_name, music_id...) when I call such as http://127.0.0.1:8000/api/musiclist/7/(GET), that required nested relationships. however I also wanna to update MusicListwith music_id, it can be implemented by use serializers.PrimaryKeyRelatedField I tried to defined two fields to Specify separately write_only and read_only,but I don't think it's a good solution. models.py class MusicList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user', related_name='musiclist') name = models.CharField('list_name', max_length=50, default='') music = models.ManyToManyField(Music) def __str__(self): return self.name serializers.py class MusicSerializer(serializers.ModelSerializer): class Meta: model = Music fields = '__all__' class MusicListSerializer(serializers.ModelSerializer): # music = MusicSerializer(many=True, required=False) music = serializers.PrimaryKeyRelatedField(many=True, queryset=Music.objects.all()) class Meta: model = MusicList fields = ['user', 'name', 'music'] validators = [ UniqueTogetherValidator( queryset=MusicList.objects.all(), fields=['user', 'name'] ) ] -
Wagtail Page get_url_parts() method is not being called
I have copied some of [this]https://stackoverflow.com/a/54561756/11225921 answer/code but the get_url_parts method is not being called at all. I am wondering if it has to do with the abstract mixin, or else I am not sure. The same method header works if I put it on my (main Page/HomePage) This is the abstract class BaseSection(models.Model): """ BaseSection abstract base class. All HomePage sections should inherit from this class. """ parent_page_types = ['HomePage'] subpage_types = [] content_panels = [] class Meta: abstract = True def get_url_parts(self, request=None, *args, **kwargs): """ Customising URL patterns for a page model http://docs.wagtail.io/en/latest/topics/pages.html#customising-url-patterns-for-a-page-model Rewrite page path to corresponding anchor of this section on the containing page. """ print("METHOD CALL") url_parts = super().get_url_parts(request=request) if url_parts is None: return None else: site_id, root_url, page_path = url_parts _cust_page_path = '#section-{}'.format(page_path.replace('/', '')) return (site_id, root_url, _cust_page_path) and this here is the Page (-mixin, correct?) class IntroductionSection(BaseSection, Page): template = 'sections/text_section.html' body = RichTextField() def get_context(self, request): print(type(self)) content_panels = BaseSection.content_panels + [ FieldPanel('title'), FieldPanel('body'), ] I use wagtail modeltranslation but that should not be the reason, because the method call works for the HomePage class HomePage(Page): parent_page_types = [ 'wagtailcore.Page', ] # The following page types (here named "sections") are standard … -
MySQL REGEXP query via Django doesn't return anything but queries in MySQL work just fine, any ideas?
I'm currently developing a website that visualizes the amount of occurrences a certain ngram has given a date range, similar to google's ngram viewer, but for my native language. My thesis adviser said we should implement a regex query that returns all the ngrams that fit the given regex. However, querying via Django gives me an empty result set, and running the query in MySQL workbench gives me the data I want. I've tried using both a raw query and Model.objects.filter as shown below. def regex(request, regexPattern): #TO MAKE WORK if(request.method == 'GET'): print(regexPattern) results = Ngram.objects.filter(ngram__regex = regexPattern) for x in results: print(x) sql = "SELECT ngram FROM ngram n WHERE n.ngram REGEXP %s AND n_number = %s" val = (regexPattern, "1") with connection.cursor() as cur: cur.execute(sql, val) myresult = cur.fetchall() data = [] #data["ngrams"] = regexPattern for x in myresult: print(x) The MySQL query is SELECT ngram FROM ngram WHERE ngram REGEXP 'du\w{0,5}' AND n_number = '1' Both for loops that print x from the resultSets from Ngram.objects.filter and the raw query print nothing, but if I run this query in my database I get a lot of rows. Here is a sample ngram ------ modumo dulay dumating … -
How I can Move Site-Packages from Virtualenv to my App folder in Django
I have some packages installed in my website, but i want to move 1 package from virtual env to Django app folder (Which i Created), I copied complete folder of package from virtual env to my App folder, but no changing showing, Please let me know the process, How i can do it. -
Django dynamic page generating
I'm learning Django, and doing a project for myself. Intro about the Project : it is a travel app, where user have to select their destinations. The destinations will be added by the admin/superuser from the Admin panel. Now I can dynamically add the Contents from the Admin panel. What I want : when a user will click on a particular destination, this should open the destination page. as the content is coming from a Database (that means if i have 1 rows in the DB it will show 1 destination). Now i would like to know how can I create webpages based on the contents that are available? Image of the code snippet of the destination in the "destinations.html", what should I add so that it will create a page when I add a new destination, as well as it will create a dynamic URL to that page. for eg. I have 1 destination, and when I click it it will open the page of the destination (That I can do by creating a new view object). But suppose I add a new destination, and it will create a Page for that 2nd destination. -
ImportError: No module named 'django' uWSGI Django Nginx Ubuntu 16.04 Python3.6
I've spent a day trying to figure this out. I'm running on Digital Ocean with Django, Python3.6, Nginx, Ubuntu 16.04, and uWSGI. Have had to install Python3.6 via deadsnakesppa and have a virtualenv which I created with mkvirtualenv --python=python3.6 myproject I am following this tutorial which I have followed before but when I try to run the below code to test the application server (not in virtualenv) uwsgi --http :8080 --home /home/user/Env/myproject --chdir /home/user/myproject/src/myproject -w myproject.wsgi I get this traceback *** Starting uWSGI 2.0.18 (64bit) on [Mon Aug 5 12:23:53 2019] *** compiled with version: 5.4.0 20160609 on 05 August 2019 11:53:48 os: Linux-4.4.0-157-generic #185-Ubuntu SMP Tue Jul 23 09:17:01 UTC 2019 nodename: myproject machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/user/myproject/src/myproject detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 3898 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8080 fd 4 spawned uWSGI http 1 (pid: … -
condition in html template
Hello I am working on the web app with Python Django and I am struggling to reate condition in my html template. I got table and I want to make the text bold in the cell if the text in the cell is equals to specified text. I tried this: <table> <tr> <td>{% if order.order_buffer %}{{ order.order_buffer }}{% else %}<b>{{ order.order_buffer }}</b>{% endif %}</td> </tr> </table> In this condition it goes straight to the else block. Any ideas? -
How and where should I store the conversion code for image files in Django?
I created a simple form in Django of which it contains only a single form input field i.e image field. My aim is to allow a user to upload an image file i.e JPEG, JPG, SVG, PNG. Once uploaded, I want to write some code that'll convert the image file to PNG and then store it in my database. How should I write this code and where do I write it? You can view my current code below. I'm a beginner in Django and could use some help. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') website/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models class Image(models.Model): """Image upload model""" image = models.ImageField(upload_to = 'media', default = 'media/sample.png') created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) forms.py from django import forms from myapp.models import Image class ImageForm(forms.ModelForm): """Image upload form""" class Meta: model = Image exclude = ('created_date',) views.py from django.shortcuts import render from django.db import … -
How to SQL code conversion to a single Django ORM query?
I'm trying to convert the following SQL query in to a single Django query in order to minimize number of executed sql queries, however I'm not able to do that except using a for-loop. I appreciate it if anyone could provide me the intended Django query SQL Query: select FUND_ID, REPORT_DATE, PURCHASE_NAV_PER_SHARE FROM FUNDS_HISTORY WHERE REPORT_DATE = ( SELECT Max(REPORT_DATE) FROM FUNDS_HISTORY fund_history where fund_history.FUND_ID = FUNDS_HISTORY.FUND_ID ) -
how to connect database programatically at runtime in #django framework
I have in my User Profile, one field to define the Database name, that user can connect. DATABASES = { 'app_data': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres_user', 'PASSWORD': 's3krit' }, 'DBNAME_1': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'priv4te' } } class UserProfile(models.Model): user = models.OneToOneField(User) dbname = models.CharField(u'Database name', max_length=100, null=True, blank=True) not connecting to 2 different database only creating in single database -
How to deal with variation in products price?
I'm creating an e-commerce website. Now I'm working on the checkout process. I have "Variation" model for products with different prices. Therefore in the checkout page, I wanted to get the new variation price instead of the original prices, can anyone help me out. products/models.py class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.DecimalField(max_digits=5,decimal_places=2) category = models.ForeignKey('Category', null=True, blank=True,on_delete=models.DO_NOTHING) slug = models.SlugField(default='hello') image = models.ImageField(null=True, blank=True) available = models.BooleanField(default=True) stock = models.PositiveIntegerField(default=100) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False,null=True) updated = models.DateTimeField(auto_now_add=False,auto_now=True,null=True) class Variation(models.Model): product = models.ForeignKey(Product_info,null=True,on_delete=models.SET_NULL) cat = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='model') title = models.CharField(max_length=100) price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) description = models.TextField(null=True,blank=True) active = models.BooleanField(default=True) objects = VariationManager() def __str__(self): return self.title carts/models.py class CartItem(models.Model): cart = models.ForeignKey(Cart,null=True,blank=True,on_delete=models.DO_NOTHING) product = models.ForeignKey(Product_info,null=True,blank=True,on_delete=models.DO_NOTHING) variations = models.ManyToManyField(Variation,null=True,blank=True) quantity = models.IntegerField(default=1) linetotal = models.DecimalField(max_digits=100,default=10.99,decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False,null=True,blank=True) updated = models.DateTimeField(auto_now_add=False,auto_now=True,null=True,blank=True) def __str__(self): try: return str(self.cart.id) except: return self.product.name carts/views.py def view(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None if the_id: new_total = 0.00 for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total cart.save() context = {"cart":cart} else: context = {"empty": True} return render(request,'carts/view.html',context) -
django mail function returning an error "SMTPserver disconnected -Connection unexpectedly closed"
I am trying to send mailto my user but django send_mail() function through an error. I tried gmail smtp ass well as yahoo. but unable to find what the problem is?? Form is perfectly working and data goes to database whenever any enquiry made. This is my views.py file from django.shortcuts import render, redirect from django.contrib import messages from django.conf import settings from .models import Contact from django.core.mail import send_mail # Create your views here. def contact(request): if request.method == 'POST': listing_id = request.POST['listing_id'] listing = request.POST['listing'] name = request.POST['name'] phone = request.POST['phone'] email = request.POST['email'] message = request.POST['message'] user_id = request.POST['user_id'] realtor_email = request.POST['realtor_email'] contact = Contact(listing_id=listing_id, listing=listing, name=name, phone=phone, email=email, message=message, user_id=user_id) # if user already made enquiry for this listing if request.user.is_authenticated: user_id = request.user.id has_contacted = Contact.objects.all().filter(listing_id=listing_id, user_id=user_id) if has_contacted: messages.error(request, 'You are already made enquiry for this listing.') return redirect('/listings/' + listing_id) contact.save() ## SEnd Mail from_email = settings.EMAIL_HOST_USER send_mail( 'Property Listing Enquiry', 'There has been a entry for ' + listing + 'Sign Into the admin panel for more info.', from_email, [realtor_email, 'ramji1493@gmail.com'], fail_silently=False, ) messages.success(request, 'Your message has been submitted. A realtor will get back to you soon.') return redirect('/listings/'+listing_id) This is my … -
Store Google OAuth2 code verifier while using DRF with DOT
I'm using Django Rest Framework with Django OAuth toolkit in order to authenticate clients of my API. Now I need to fetch some user data from Google API (calendar, in this example) and I'm stuck on storing code verifier between Google authorisation redirect and callback. The following is the simple code sample: def random_string(length=10): import string, random password_characters = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(password_characters) for i in range(length)) rs = random_string(60) def get_flow(state=None): flow = Flow.from_client_secrets_file( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scopes=[ 'https://www.googleapis.com/auth/calendar', ], state=state, ) flow.redirect_uri = 'http://127.0.0.1:8000/api/google_calendar_import_callback/' flow.code_verifier = rs return flow I need to share rs (code_verifier) between these two requests, but as I'm not using sessions, I can't just put it there. Storing it in some user field is not a solution either, as user might use different devices, overwriting this code. So, the only option I see is to extend DOT's Token model, adding the field to store code_verifier for each access_token, but that doesn't seem to be the best (or even remotely beautiful) solution. Is there anything better? My redirect and callback views are the following: class CalendarImportRequestView(APIView): permission_classes = (IsAuthenticated,) @staticmethod def get(request): auth_flow = get_flow() auth_url, state = auth_flow.authorization_url(prompt='consent') result = { 'auth_url': auth_url, … -
Why I can't upload images from django admin to a directory that should simulate a static files live server?
When I upload an image from the admin panel I want this image to be uploaded in a specific directory in my Django project, still the directory is always empty. I changed my settings.py multiple times but I think the configurations of MEDIA_ROOT and MEDIA_URL are fine. static_cdn_test is the directory in my main Django project folder, it contains 3 directory: media, static, staticfiles. # relevant part of settings.py STATIC_URL = '/static/' LOCAL_STATIC_CDN_PATH = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn_test') STATIC_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] MEDIA_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'media') MEDIA_URL = '/media/' # my model class Article(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.FileField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) Inside static_cdn_test/media should appear a folder named image which should contains all the uploaded images but nothing happens. Any help is really appreciate, thanks all. -
Does the atomic decorator affect all the methods in the chain in Django?
I have the following models set up in Django: from django.db import models, transaction class X(models.Model): ... def do_something(self): ... self.save() class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) def do_something(self): ... self.save() def save(self, *args, **kwargs): super(Y, self).save(*args, **kwargs) self.x.do_something() class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) @transaction.atomic def save(self, *args, **kwargs): super(Z, self).save(*args, **kwargs) self.y.do_something() Basically, whenever a Z object is saved, this triggers the do_something() method in the Y object, which then saves itself, and in doing so, triggers the do_something() method in the X object. I want the whole chaining to be atomic, so that if a Z object is saved, its corresponding Y and X objects must be saved as well. I have the decorator only in the save() method in the Z class. Is this the correct way to do this? Or, should the decorator be added to all the other methods in the chain? Does the decorator automatically affect all the methods in the chain or should it be explicitly added? Thanks for any help. -
How to get Foreign Key ID to show two models in DetailView?
I've created these two models: "Property" and "Bedroom". I've created a Class Based View, DetailView to show the details from Property, but now I need to show not only the property details but also the bedroom details. # models.py class Property(models.Model): property_reference = models.CharField(db_column='Property_Reference', max_length=10) # Field name made lowercase. address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase. post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase. type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase. bedrooms = models.IntegerField(db_column='Bedrooms', blank=True, null=True) # Field name made lowercase. bathrooms = models.IntegerField(db_column='Bathrooms', blank=True, null=True) # Field name made lowercase. usual_cleaning_requirements = models.CharField(db_column='Usual_Cleaning_Requirements', max_length=250, blank=True, null=True) # Field name made lowercase. notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. feature_image = models.ImageField(null=True) class Meta: db_table = 'Property' def __str__(self): return self.property_reference def get_absolute_url(self): return reverse("properties:property_detail",kwargs={'pk':self.pk}) class Bedroom(models.Model): type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50) bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30) image = models.ImageField(null=True, blank=True) ensuite = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE, related_name='bedroom') And I've created this view: class PropertyDetailView(DetailView): template_name = 'properties/property-detail.html' model = Property def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['bedrooms'] = Bedroom.objects.get(property = … -
Django: How to Set Default Field Value By Model Method
I have a simple Model. I want to calculate a default value for one of its fields (let's call it score) based on the some of the fields of the same model: My ideal way to do it is as so: class ModelA(models.model): field_1 = models.IntegerField() field_1 = models.IntegerField() score = models.IntegerField(default=self.calculate_default()) def calculate_default(self): default = (self.field_1 + self.field_2) / 2 return default Problem: the calculate_default method does not have access to self. One solution I tried was overriding the save() method. The problem is that it prevents the user to further change the score field. Another method I searched was to override the inti of the class. But according to django it might have consequences if not implemented correctly. What is the cleanest way to achieve this? How can I set the default of a field to be calculated from other fields of the same model such that it could be later changed by the user? I have a hunch that classmethod is the way to go but I haven't been able to pull it off yet. -
Get and transfer data using an API
I have to develop an API to manage data between my Database in PostGreSQL and my website in Django. I'm actually looking for the best way to manage and transfer this data, what I actually found on different topics / sites is the Django Rest Framework to develop a Rest API in Django, here I would use a JavaScript framework for the front like React, Angular or VueJS (any tips about which one to choose ? ). I was wondering if there was other solutions that would be interesting ? I've been searching about FTP or things like this. Thanks, -
how to set a timezone.now on django
Hello i'm strugling trying to set a variable with a date.today. I don't want to set an auto_now i want to set a variable with the date of the access of the user. i'm not quite shure if i should create a Field with an function by default or just set a variable on views.py i've tried both and i'm getting lost models.py: task = models.CharField(max_length=150) topic = models.CharField(max_length=150) how = models.TextField(max_length=600) start = models.DateField(blank=False, auto_now_add=True) end = models.DateField(blank=False) updated_at = models.DateTimeField(auto_now=True) views.py: class DetailView(DetailView): template_name = 'details.html' model = To_do now = datetime.today def get_queryset(self): return To_do.objects.annotate( delta2=ExpressionWrapper(F('end') - F('now'), output_field=DurationField())) i want to get the today date to display a countdown (end - now) every time the user open the page -
Catch Django order_by exception
I want to let user get objects by sorting them via API: example.com/foo?sort_by=STR. I'm going to use STR in .order_by. I found it's difficult to catch FieldError if Django cannot sort by STR (if STR keyword doesn't exist in the field) because QuerySets are lazy. foo_set = Foo.objects.order_by('bar') # won't throw an exception return foo_set[: 10] # will throw FieldError I cannot check if STR field exists before because I want to let user sort in the reverse sequence (foo.order_by('-bar')). So I put foo_set[0] in try but it's horrible (exception if foo_set is empty, hardcoded getting the first element). What way to check would you use? -
Why I'm not able to open django app on heroku?
I'm trying to test out my app but uploading it to heroku but when I try to open it the following error appears I tried to heroku restart but nothing changes I have already pushed it and made it live, is just when I try to open it 2019-08-05T10:28:35.985995+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=gentle-badlands-35223.herokuapp.com request_id=1a6f1655-5d02-43c7-b629-c2b4897e76bf fwd="83.174.32.242" dyno= connect= service= status=503 bytes= protocol=https 2019-08-05T10:28:36.411718+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=gentle-badlands-35223.herokuapp.com request_id=d4d9f0e0-8495-43e2-929b-8664f88503e7 fwd="83.174.32.242" dyno= connect= service= status=503 bytes= protocol=https 2019-08-05T10:29:31.130647+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=gentle-badlands-35223.herokuapp.com request_id=2f3ab1c6-7b2f-47fd-827e-c4fc1725eda3 fwd="83.174.32.242" dyno= connect= service= status=503 bytes= protocol=https 2019-08-05T10:29:31.390998+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=gentle-badlands-35223.herokuapp.com request_id=088bbe15-3618-48d9-8c59-3a0d88d170f1 fwd="83.174.32.242" dyno= connect= service= status=503 bytes= protocol=https -
Import File in django
Here"s an Error I have and I can't solve: Cannot import name "File" from 'uploadapp.models' The picture below makes it better to understand. Thanks in advance for your help. enter link description here -
import xls file by django in problem in date field is not import in database
I was upload by admin django by select excel file that in available date but no fetch the date by excel file and not import date. -
How to manage the separate session for same browser Admin & Frontend in django
I'm looking for a way to separate the session handling for the admin part of a site and the frontend. A person should be able to log in to the admin (only if he has is_staff and/or is_superuser). He should have to be able to login with another username into frontend. So basically it's like two separate sessions for the admin and frontend. Login/Logout and Permission-check functionality is not a problem, different sessions is the problem. Any ideas? Thanks, -
when in try to access mysql view using django model it throws an error
I want to access the records in mysql view using django filter but it throws an error try: p = PartnerPayBillSummaryDetails.objects.all() print(p) except Exception as e: print(e) Error: OperationalError: (1054, "Unknown column '66_1_partner_pay_bill_ageing_dtl.id' in 'field list'")