Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django way to represent languages of users
I have the Follower class class Follower(models.Model): language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) and the Lang class: class Language(models.Model): code_name = models.CharField(max_length=6, null=True, blank=True) def __str__(self): return self.code_name Where looking for negative value e.g user_langugae != 'ar I get the following lookup: SELECT * FROM "instagram_data_follower" WHERE NOT ("instagram_data_follower"."id" IN (SELECT U1."follower_id" FROM "instagram_data_follower_language" U1 INNER JOIN "instagram_data_language" U2 ON (U1."language_id" = U2."id") WHERE U2."code_name" = ar))) Which takes so longggggg over 20 minute sometimes. Lookup for equal is much faster. I think I need to redesign the schema so languages will be kind of bitmap. Can you suggest a better way to look up on negative condition for one to many field ? Most of my lookups are user_langugae != 'ar AND user_langugae == 'he' I Saw this: https://github.com/disqus/django-bitfield btw -
How to use Docker Image in Django?
I made a docker image and I want to use this image in Django like a url. I always find examples about how to set up docker to django but I want to use it with a single line of url. I found a flask code but I really don't know how to convert it. So here is my flask app.py file: @app.route("/index", methods=['POST']) def index(): url = "http://localhost:5000/index" #this is my link to docker file payload = {"text": request.form["input_text"]} response = json.loads(requests.request("POST", url, json=payload).text) return jsonify(response) How can I write this code with Django? -
Django: Abstract base class for managing db_table
I'm trying to build my second django (and python for that matter, my first project being the django tutorial :)) project. since this is supposed to be something real i'd like to be thorough and build a good code structure before i go into the meat of the project. I have a couple of simple models like this class Task(models.Model): name = models.CharField(max_length=50, null=False) description = models.CharField(max_length=255, null=True) dueDate = models.DateTimeField() I'm using PostgreSQL and i set up my models to use the app label as a database schema by defining the meta class of each model like this class Meta: managed = True db_table = 'app_name\".\"modelname' This works well. But i have to do this for every single model. I want to keep it DRY though. So what i'm trying to do now is to have an abstract base class that does this automatically so i tried the following: class SchemaModel(models.Model): class Meta(): abstract = True managed = True db_table = AppConfig.label+'\".\"'+self.__class__.lower()+'s' (the base class was then inherited of course and i took the nested Meta class out of the normal models) this didn't work though because self isn't accessible in Meta after consulting the documentation i tried this: … -
How to reference S3 bucket inside views within a Django project?
I'm using an S3 to deliver static content. I only use Django as a RESTful API, my frontend is built using React. I do however use one HTML file as a template. The HTML file is only used as part of the HTML content of an email message sent by my server. I plan on moving this HTML file to my S3 Bucket. I'm trying to wrap my head around how I may reference such file within my S3. Normally to reference a standard HTML template in django, it can look something like this: html = render_to_string('email/email_confirm.html', context) email being the name of the folder inside templates. I know how to work with pathing within an S3, but how can I pull up and reference that object directly within my view below? I have already configured all my S3 settings class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request, format='json'): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: # GENERATE EMAIL CONFIRMATION TOKEN user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token # GENERATE EMAIL CONFIRMATION TEMPLATE current_site = get_current_site(request).domain relative_link = reverse('users:email-verify') # CHANGE TO HTTPS in PRODUCTION absurl = 'http://'+current_site+relative_link+"?token="+str(token) email_body = 'Hi '+ user.username+', Please use … -
django passing id of the first saved form to the second form
My model has one to many relationships, when the user saves the first forms he will navigate to another form and the user should be able to fill up the second form and save it. Because it is a one-to-many relationship I want to pass the id instance of the first saved entry to the second form. However, when I fill up the second form and try to save it the data for the second form is not saved. I am not sure what I am doing wrong causes the data on the second form not to be saved. view.py that saves the first forms ef add_bank_form(request): if request.method == 'POST': form = BankForm(request.POST) natural_person_form = NaturalPpersonPform(request.POST, request.FILES) OwnShares = OwnSharesInOtherCompanyForm(request.POST, request.FILES) if form.is_valid() and natural_person_form.is_valid(): form = form.save() natural_person = natural_person_form.save(commit=False) natural_person.domesticbank = form natural_person.save() share = OwnShares.save(commit=False) share.domesticbank = form share.save() return HttpResponseRedirect('/add_source_of_income') else: form = BankForm() natural_person_form = NaturalPpersonPform() OwnShares = OwnSharesInOtherCompanyForm() return render(request, 'add_domestic_bank.html', {'form': form, 'natural_person_form': natural_person_form, 'OwnShares': OwnShares}) view.py that saves the second form def add_source_of_income(request): if request.method == 'POST': get_bank_id = DomesticBank.objects.order_by('-pk')[0] form = SourceOfIncomeForm(request.POST, request.FILES, instance=get_bank_id) if form.is_valid(): form.save() return HttpResponseRedirect('/DisplayBankRisk') else: form = SourceOfIncomeForm() return render(request, 'add_income_source.html', {'form': form}) -
Django - set model's `CharField` primary key from processed `ImageField` data
This is maybe a poor way to ask this question, as I haven't yet tried anything since I'm not sure if it's even possible without a bunch of custom JS added to the admin. Given a model such as: class MyModel(models.Model): sku = models.CharField('SKU', max_length=20, primary_key=True) bar_code = models.ImageField(upload_to='images/barcodes') I want the user to select an image which will be a photo of a product's barcode. The image then needs to be processed to scan for the barcode (I'm using pyzbar) and this value should be saved to the primary key field sku. Since I can't save the model without a primary key, and I need to upload the image field to scan the barcode to discover the value to be used for the primary key, I'm thinking that the only way to do this would be to use some client side JS in the admin to upload the image to a temp location using a DRF endpoint (or similar), read the barcode and return that value to the client which could then set the value of sku with some basic javascript. Then the model can be saved and image uploaded (a second time). Is there a more straightforward way … -
ParentalManyToManyField in Wgarail works with normal model but not with orderable
Hello everyone I used the ParentalManyToManyField like described in here in the first step https://www.accordbox.com/blog/wagtail-tip-1-how-replace-parentalmanytomanyfield-inlinepanel/ and it worked, but after that I needed to use it in an Orederable Model like this: class GalleryCategory(models.Model): name = models.CharField(max_length=50) panels = [ FieldPanel("name"), ] def __str__(self): return self.name class GalleryMedia(Orderable): category = ParentalManyToManyField("gallery.GalleryCategory", blank=True) gallery = ParentalKey( "gallery.Gallery", on_delete=models.CASCADE, related_name="media", null=True ) image = models.ForeignKey( "wagtailimages.Image", on_delete=models.CASCADE, related_name="+", null=True, blank=True ) video_url = models.URLField(blank=True) video = models.ForeignKey( "wagtailvideos.Video", related_name="+", null=True, blank=True, on_delete=models.SET_NULL, ) show_large = models.BooleanField(default=False) show_on_homepage = models.BooleanField(default=False, verbose_name="Show on HomePage") panels = [ ImageChooserPanel("image"), FieldPanel("video_url"), VideoChooserPanel("video"), FieldPanel("show_large"), FieldPanel("show_on_homepage"), MultiFieldPanel([FieldPanel("category", widget=CheckboxSelectMultiple),]), ] class Gallery(Page): content_panels = Page.content_panels + [ InlinePanel('media', label=_('Gallery Media')) ] I registered the Category Model in the admin dashboard like this: class GalleryCategoryModelAdmin(ModelAdmin): model = GalleryCategory menu_icon = "edit" menu_order = 300 add_to_settings_menu = False exclude_from_explorer = ( False ) list_display = ("name",) search_fields = ("name",) modeladmin_register(GalleryCategoryModelAdmin) I can add the categories just fine, and they are displayed correctly in the admin dashboard Gallery page as checkboxes, but when I choose a certain category for some Media and then publish the page, all the categories check boxes that I checked are gone! Anyone knows why? -
Django3: accounts/password_reset does not use admin.site.site_header
I have an app main/ ├── asgi.py ├── celery.py ├── __init__.py ├── settings.py user/ ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── ... ├── models.py ├── tests.py ├── urls.py └── views.py In admin.py the admin page title is set like this: from django.contrib import admin admin.site.site_header = settings.HOME_TITLE Which works on localhost:8000/admin/. But http://localhost:8000/accounts/password_reset/ still shows the standard Django Administration title. Is there a way to change that consistently or would I have to create my own template for this? -
How to make this model?
I am creating a Calorie Log website using Django. One creates an account, and can start logging the amount of calories he consumed and burnt on a particular date, then it shows whether on that day he consumed or burnt more calories.The User can store frequently eaten food and frequent exercise that he does so that when he adds the data he can use that item class Food(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) food_name = models.CharField(max_length=50, null=True, blank=True) calories = models.IntegerField(null=True) food_pic = models.ImageField(default="default_food.jpg", null=True, blank=True) def __str__(self): return f"{self.food_name}" class Exercise(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) exercise_name = models.CharField(max_length=100, null=True, blank=True) calories = models.IntegerField(null=True) exercise_pic = models.ImageField(default="default_exercise.png", null=True, blank=True) def __str__(self): return f"{self.exercise_name}" Porblems > How do I make the model in which I can store the data of food eaten and exercises done on that particular day. I tried making a model and the creating its inlineformsets but it did'nt work, at this point it is very messy. The web page will compose of the section where user will be able to select a food item and the amount he consumed on that particular day. Same for the exercises, that data is what I want to store. I … -
Using Python Libraries in Django
invoice python script Hello! I would appreciate if someone could help me with a doubt I have about using Python libraries in Django. I will try to be as clear as possible so here it goes: In my job I work with invoices that are all saved in a specific directory (PDF files). In my job I am interested in only one specific value in a row which is a number. My job is to extract that value from all the invoices and sum them all. So, I made a python script in which I use the libraries Pandas, os and PDFplumber and it works great. In code.png, you can see the loop I use to extract the row and value that I want by using PDFplumber and then sum all these values. In invoice.png you can see how PDFplumber divides the invoice in rows and in columns. So, here is the thing: I want to deploy a Django App so that other people in the enterprise can use the python script I use ( they don't know anything about Python programming). So, I would want to deploy a Django app in which they can upload the directory with all … -
Unresolved attribute reference 'count' for class 'ManyToManyField'
Hey Guys i m stuck in pycharm 'models.py' def total_likes(self): return self.likes.count() pycharm is giving me 'Unresolved attribute reference 'count' for class 'ManyToManyField' this error what to do? -
Take my data from my computer and Verify that data is not stolen
As a Python programmer recently I received a small project to edit and add some functions. (the project is Python/Django) But while I was working on it, I noticed something unusual, which is the presence of some python libraries(hashlib and others), which can take my data(Gmail accounts, passwords, chrome bookmarks . . .) from the computer. This Script is an example from the code. import hashlib import logging import re import pandas as pd from file import reader logger = logging.getLogger(__name__) def load_data(user_id, project_id, columns: dict): group_files = {} df = pd.DataFrame(None) for id_, column in columns.items(): group = column['group'] if group not in group_files: df_file = reader.load_file(user_id, project_id, group) group_files[group] = df_file if group_files[group] is not None: if column['content'] in group_files[group].columns: df[column['content']] = group_files[group][column['content']] return df def get_hash(string: str): return hashlib.md5(string.encode()).hexdigest()[:5] My question is: How can I know if they are taking my data from the computer or not? Thanks in Advance. -
django-filter and django-tables2 only show rows were boolean = true
I've been trying to figure out how to only show rows in my table where a column value is set to true using Django-filter and Django-tables2 but I can't seem to get the code working. I am able to generate the table and generate the filters, but depending on who is signed into the app, I only want to show records where an 'is_reviewed' column is set to true. I thought I had it working using the following line in my views.py file but then discovered it was not applying the filter at all to my queryset: # only show scenarios that have been reviewed and published, or scenarios that the user submitted. # self.table_data = self.table_data.filter(Q(is_reviewed=True) | Q(submitter = request.user)).order_by("-id") https://github.com/alexandroidii/cst8333 This is what I have so far: Views.py class FilteredScenarioListView(SingleTableMixin, FilterView): model = Scenario template_name = "rlcs/scenario_list.html" table_pagination = {'per_page': 5} ordering = '-id' def get(self, request, *args, **kwargs): is_reviewer = request.user.groups.filter(name='reviewer').exists() or request.user.is_superuser if is_reviewer: self.table_class = ReviewerScenarioTable self.form_class = ReviewerScenarioFilterForm self.filterset_class = ReviewerScenarioFilter elif request.user.is_authenticated: self.table_class = SubmitterScenarioTable # only show scenarios that have been reviewed and published, or scenarios that the user submitted. # self.table_data = self.table_data.filter(Q(is_reviewed=True) | Q(submitter = request.user)).order_by("-id") self.form_class = SubmitterScenarioFilterForm self.filterset_class … -
Django Bad Request (400) Debug=False
I'm trying to publish my site, i configured all settings (nginx & gunicorn) This settings works well DEBUG=True ALLOWED_HOSTS = ['localhost','127.0.0.1','domain.com','www.domain.com'] However, when i edit the DEBUG=True to False DEBUG=False i got this error on browser Bad Request (400) i also tried these setttings ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['domain.com','www.domain.com'] (before posting this question i checked this answer Django gives Bad Request (400) when DEBUG = False ) -
Form Validation Method for Class-based form views
I hope you guys could tell me how to use validation methods in my forms.py for a single field. My view is a generic.FormView and my form is forms.Form. Here is my view: class ClassSetupView(OrganisorAndLoginRequiredMixin, generic.FormView): template_name = "leads/class_setup.html" form_class = ClassSetupForm def get_success_url(self): return reverse("class-setup-sucess-page") def form_valid(self, form): # Some Other Code return super(ClassSetupView, self).form_valid(form) Here is my form: class ClassSetupForm(forms.Form): date = forms.DateField(help_text="Year-01-01",) I read some other websites that show an example of their form validation as: class RenewBookForm(forms.Form): renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).") def clean_renewal_date(self): data = self.cleaned_data['renewal_date'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) # Check if a date is in the allowed range (+4 weeks from today). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data The website's example has a view that is a function and not a class-based view(FormView) like mine. This method seems pretty simple and straightforward to me. However, I don't know if I can use clean_date(self): for my form, since I have … -
Best way to define a location/latlon field in a django model
I have a model "Store" which somehow needs to store the address, latitude, and longitude of the "Store" instance so I can show the exact location on the map later. I tried to store lat long as CharField in separate fields but is there any better solution for this purpose? maybe PoinField or DecimalField? lat = models.CharField(max_length=50) lon = models.CharField(max_length=50) -
django: object has no attribute 'cleaned_data'
I'm trying to make a registration page for my project. Standart model User is not enought for me, so I created another model named Profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=1, choices=SEX_CHOICES, default='М', verbose_name='Пол') third_name = models.CharField(max_length=30, verbose_name='Отчество') grade = models.CharField(max_length=2, choices=GRADE_CHOICES, default='1', verbose_name='Класс обучения') age = models.PositiveSmallIntegerField(default=7, verbose_name='Возраст', validators=[ MaxValueValidator(100), MinValueValidator(4) ] ) school = models.ForeignKey(School, on_delete=models.PROTECT, verbose_name='Учебное заведение', blank=True, null=True, default=None) interest = models.ManyToManyField(OlympiadSubject, verbose_name='Интересующие предметы') On both, User and Profile I created a ModelForm: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('third_name', 'sex', 'grade', 'age', 'school', 'interest') And wrote a view for registration: def create_profile(request): if request.method == 'POST': user_form = UserForm() profile_form = ProfileForm() if user_form.is_valid() and profile_form.is_valid(): User.objects.create(**user_form.cleaned_data) Profile.objects.create(**profile_form.cleaned_data, user=User) return redirect('/login') else: profile_form.add_error('__all__', 'Данные введены неверно!') else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'users/profile_create.html', { 'user_form': user_form, 'profile_form': profile_form }) and of'course i have a template for that: {% extends 'main/layout.html' %} {% block title %} Some text {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <button type="submit">Сохранить изменения</button> </form> {% endblock %} but … -
django.db.utils.ProgrammingError: column app_poll.approve_id does not exist LINE 1:
I have two two models, 'Poll' and 'Approve'. The 'Approve' model is created later and appears much later in the migrations and i want to reference it as Foreign key in the Poll model. If i delete all tables from the database and run migrations, i get an error that says column 'approve_id' does not exist. class Poll(models.Model, ContentTypeMixin): date = models.DateTimeField(auto_now_add=True, verbose_name='Date') comment = models.TextField(blank=True, verbose_name=_('Comment')) approve = models.ForeignKey('Approve', on_delete=models.CASCADE, null=True, blank= True, verbose_name=_('Final Approval By')) class Approve(models.Model, ContentTypeMixin): name = models.TextField(blank=True, verbose_name=_('Name')) -
django-elasticsearch-dsl: how to add script to filter?
I have a 'MovieDoc' document and inside it a ListField called 'actors' that contains a list of ObjectFields with properties such as 'last_name', 'first_name', 'country,' etc. When running a query with Django ElasticSearch DSL, I would like to filter movies by the number of actors they feature (i.e. by the length of the values in the 'actors' ListField). As far as I understand, this should be done using script-filtering (https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html). However, I do not understand how I can apply the ElasticSearch script filtering with django-elasticsearch-dsl. I have tried something like this in different combinations but to no avail: search_query = 'battle' results = MovieDoc.search().query(search_query).filter(script={"script": ["doc['actors'].values.size() > 1"]}) -
Get address from Google maps without API
For educational purposes my teacher has given me a task to figure out how to get chosen address from Google map without API. As i see the one way to use maps without api is 'Share' on google maps site > 'iframe' tag in html. I can easily put different addresses from db to render different locations. But i need to let user to choose location and save this location in db. I have tried to get 'div' with place address but got a "Blocked a frame with origin 'my.site' from accessing a cross-origin frame." Interesting that i can find this div if i inspect iframe element using ctrl+shift+c AND after that can find it via js in console, but because of cross-origin problem i cant do it in my code. I have thought about getting requests but in 'network' tab in DevTools, i don`t see any looks like address info. All the information i found is about using google api key, but the challenge is to do this without it. Maybe someone will have any ideas? If it matters, i use Django for web-application. -
Django: Avoid rendering as variable in template
I just started learning django for a few day. Django's templating system looks fascinating. but currently I am facing an issue. I need to print this kind of text in my webpage multiple times through template. She {{ was }} a very {{ helpful }} and {{ attractive}} girl. But whenever I try to use this in template, it thinks those words are variable thaI am referring, and vanishes them from the output due to not getting a value. So the output becomes, She a very and girl. I completely understand that this is the intended behaviour, but in some case I am trying to tell the rendering engine to render that as it is. Is there any filter or workaround?? [ I have to use them inside the template, and they can't be passed through variables as string] -
Django: access to attributes of custom model field from html template
I implemented a custom model field: class CustomCharField(models.CharField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.my_attr = "MY_ATTR" Now I want to be able to display that additional attribute when I'm iterating over all model's fields in change_form_template: {% block field_sets %} {% for fieldset in adminform %} {% for line in fieldset %} {% for field in line %} {{ field.field }} {% if field.field.my_attr %} {{ field.field.my_attr }} {% endif %} {% endfor %} {% endfor %} {% endfor %} {% endblock %} Unfortunately my_attr is not visible. I was searching the proper method in the django docs but without any success. I was also trying to use the custom form_class (inheriting the django.forms.fields.CharField) -
why do static files don't work in Django?
here is my settings STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] i did this command python manage.py collectstatic it shows 0 static files copied to 'C:\Users\ALOSTATH\Desktop\Xv\Assets-Tracking-Testing-main\staticfiles', 169 unmodified. when i run it locally, this error is displayed django.core.exceptions.SuspiciousFileOperation: The joined path (S:\cdnjs.cloudflare.com\ajax\libs\jquery-easing\1.4.1\jquery.easing.min.js) is located outside of the base path component (C:\Users\ALOSTATH\Desktop\Xv\Assets-Tracking-Testing-main\static) [22/Apr/2021 19:24:38] "GET /static/https%3A/cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js HTTP/1.1" 500 59 any idea? NOTE: i have two folders, static and staticfiles in the project -
404s in production only
First-time django deployer here. My endpoints work in local dev, but in production some of them are responding with a 404. The troublesome seem to be the allauth ones in particular. e.x: accounts/login/ accounts/signup/ accounts/confirm-email/ ... I've confirmed that these endpoints exist in production by hopping into the shell and checking django.urls.get_resolver. I'm using cookiecutter-django so I also confirmed that ACCOUNT_ALLOW_REGISTRATION is set to True. Anything else I should check? -
Join Foreign Key Table Django QuerySet
Hi im learning Django Queryset,but i get confused when i want to use queryset django to join table,instead of using django raw query i want to learn django queryset In my case i want to fetch RiskIdentification data class Activity(models.Model): act_name = models.CharField(max_length = 40) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) class ActivityDetail(models.Model): act_risk_assessment = models.ForeignKey(RiskAssessment, on_delete=models.CASCADE) act = models.ForeignKey(Activity, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) class RiskAssessment(models.Model): name = models.CharField(max_length = 30) date = models.DateField() email_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) class RiskIdentification (models.Model): idn_description = models.CharField(max_length = 30) idn_risk_assessment = models.ForeignKey(RiskAssessment, on_delete=models.CASCADE) risk_type = models.ForeignKey(RiskType, on_delete=models.CASCADE) class RiskMitigation (models.Model): mtg_description = models.CharField(max_length = 30) identification_risk = models.ForeignKey(RiskIdentification, on_delete=models.CASCADE) it will look like this in raw query SELECT idn_descriptiom FROM RiskAsessment RA JOIN RiskIdentification RI on RA.id = RI.idn_riskAsessment JOIN ActivityDetail AD JOIN AD.act_risk_assessment = RA.id JOIN Activity A on A.id = AD.act Please help me how django query will looks like,and describe it