Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my URL doesn't activate view in django?
Here is the thing i'm trying to do: There are few tv channels as image links and they will have some information inside channels. I managed to create tv channels as a list, they look like a link but they don't work like link. I've created slug area for each channel that takes from it's own name and generates slug auto. And with get_absolute_url i take it's url in the below code you'll see; This is my model : class Channels(models.Model): name = models.CharField(max_length=50, null=False, blank=False, verbose_name="Tv Kanalı") logo = models.ImageField(upload_to="channels/images/", verbose_name="Tv Logosu", blank=False) slug = models.SlugField(null=True, unique=True, editable=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Channels, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('channel-list:campaigns', kwargs={'page_slug': self.slug}) This is my main urls: urlpatterns = [ path('admin/', admin.site.urls), url(r'', include(('tvekstra.apps.core.urls', 'home'), namespace='home')), url(r'^user/', include(('tvekstra.apps.user.urls', 'login'), namespace='user')), url(r'^channels/', include(('tvekstra.apps.tvchannels.urls', 'main'), namespace="channel-list")), This is channels urls: urlpatterns = [ url(r'', views.channel_list, name='channels'), url(r'^(?P<page_slug>[-\w]+)/$', views.campaign_list, name='campaigns'), ] This is my views: def channel_list(request): channels = Channels.objects.all() return render(request, 'channel.list.html', {'channels': channels}) def campaign_list(request, page_slug): channel = get_object_or_404(Channels, slug=page_slug) return render(request, 'campaign.list.html', {'channel': channel}) And this is my template: {% for channel in channels %} <div class="col-3 text-center channels"> <a href="{{ channel.get_absolute_url }}"> <img src="{{ channel.get_image }}" … -
Converting Sql query with joins To django orm query
I am trying to convert an Sql query to Django orm query: SELECT * FROM table1 JOIN table2 ON table1.field1 = table2.field1 JOIN table3 ON table3.field = table2.field JOIN table4 ON table4.field2 = table3.field2 JOIN table5 ON table5.field = table2.field Any help apreciated! -
Django DB connection custom SQL parameters
I need to perform a batch update since the ORM seems to be a bit slow at this. Since I am updating strings that could contain single quotation marks, e.g. Mc'Donald, I cannot simply template a string variable with all of the attributes. The documentation recommends the following: cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) Question: How do I apply this correctly for the below use case? Technical Details: Django 3.0.2 I am generating a SQL string and then calling it as follows: from django.db import connection people = [{"name": "Person A", "age": 15, "height_m": 1.83, "id": 5}, {"name": "Person B", "age": 19, "height_m": 1.73, "id": 45}] sql = "" params = [] for p in people: sql += 'UPDATE people SET name = %s, age = %d, height_m = %d WHERE id = %d;' params.append(p['name']) params.append(p['age']) params.append(p['height_m']) params.append(p['id']) with connection.cursor() as cursor: cursor.execute(sql, params) cursor.connection.commit() This throws the following error: ValueError: unsupported format character 'd' (0x64) at index 104 -
How to have multiple AUTH_USER_MODEL in django
I have two different app that has separate models that inherits from AbstractionBaseUser like below # in doctor/models.py ... class Patient(AbstractBaseUser): email = models.EmailField(blank=True, unique=True) phone_number = models.IntegerField(blank=False, unique=True) USERNAME_FIELD = 'phone_number' REQUIRED_FIELD = ['phone_number', 'email'] ... # in Patient/models.py ... class Patient(AbstractBaseUser): email = models.EmailField(blank=True, unique=True) phone_number = models.IntegerField(blank=False, unique=True) USERNAME_FIELD = 'phone_number' REQUIRED_FIELD = ['phone_number', 'email'] ... Both models have different fields # in settings.py AUTH_USER_MODEL = [ 'doctor.Doctor', 'patient.Patient' ] I tried to do this but in making migration it tells me that it must be a single model AssertionError: ForeignKey(['doctor.Doctor', 'patient.Patient']) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' I read docs but I couldn't find any help How can I fix this and how can I have multiple AUTH_USER_MODEL -
Django - Mark a field as favorite
Thanks in advance to anyone who takes the time to respond to this! I have two models, one showing a list of reports and one containing whether or not a user has favorited a report from the list. In the HTML, I'm looping through one model to display all reports that haven't been favorited and the other model to show favorited, so separating them by category, essentially. I'd like to use a checkbox to indicate whether or not a report has been favorited. The functionality works when marking as favorite in the admin section, but how would I introduce this in the HTML itself? Here is my code: models.py from datetime import datetime from django.utils.text import slugify from hitcount.models import HitCountMixin, HitCount from django.contrib.contenttypes.fields import GenericRelation from django.contrib.auth.models import User class ReportDirectory(models.Model): report_name = models.CharField(max_length=300, unique=True, blank=False) report_desc = models.TextField() report_type = models.CharField(max_length=300) report_loc = models.TextField() slug = models.SlugField(unique=True, max_length=300) last_update = models.DateTimeField(null=True) main_tags = models.CharField(max_length=300) view_count = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') # Renames the item in the admin folder def __str__(self): return self.report_name # Creates and saves a slug based on the report_name if a slug does not already exist def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.report_name) … -
how to use background_process in django class based views.?
This is my view file. class MyView(View): def send_notification(): cls_obj_ = Process_Class_View() cls_obj_ .notifications(self.request.user.id) def get(self, request): if request.user.is_authenticated: result = self.send_notification() return HttpResponse('result') This class is in another file.Im import thin cls in view file. class Process_Class_View: def noti_to_user(self,id): print("notification send to user") @background(schedule=0) def notifications(self,id): noti_to_user(id): Still call is not going to notifications().How can we use background process in class based view in django.. -
Force setup X-Frame-Options Django
I tried different methods to setup X-Frame-Options to 'SAMEORIGIN' in the Django-server responses, but it wasn't help: I removed XFrame package from the middleware in settings.py. I putted X_FRAME_OPTIONS='SAMEORIGIN' to settings.py I added 'X-Frame-Options' to response object with the same value in my view in which I wanted to use the <iframe> I tried to add @xframe_options_sameorigin decorator to my view. I also changed /etc/apache2/apache2.conf, putted Header always set X-Frame-Options "SAMEORIGIN" into it. Then I tried to restart apache2 service after all my actions but the result always the same: X-Frame-Options setted as 'DENY'. My Django version is 2.2.4. -
Is it possible to serve more than one django project under same domain?
I have a site say, localdjangosite.com and I already have a django application running on that domain at url localdjangosite.com/site1/. For this I have a virtual host set up inside apache sites-available directory as follows, I used mod_wsgi also. WSGIScriptAlias /site1 /path/to/the/django/codebase/wsgi.py <Directory /path/to/the/django/codebase/> Require all granted </Directory> And with that, that site1 is working well. Now I want to have one more site under the same domain like localdjangosite.com/site2/. And when I tried to configure apache like below I face page not found error. WSGIScriptAlias /site2 /path/to/the/django/codebase/for/site2/wsgi.py <Directory /path/to/the/django/codebase/for/site2/> Require all granted </Directory> When I configured like that and visited the url localdjangosite.com/site2/, It shows Page not found error and it displays the url configurations of the site1 instead of site2. Here site1 and site2 are really two different django projects and they have different apps inside and server different purpose. So I really don't understand what is going on? what is wrong? Could someone please help me to understand it and host two or more django projects under same domain? -
How I can reduce logic of hande form in next Django view?
I'm studing a django course right now. Teacher showed how find short route with ascross points by graph algorithm. He writed many code in view, I think it's some dirty. I shorten piece of code by using session in RouteSession class. But there is still many code. Should do any thing in this case? Thanks. def find_routes(request): if request.method == "POST": form = RouteForm(request.POST or None) if form.is_valid(): data = form.cleaned_data from_city = data['from_city'] to_city = data['to_city'] across_cities_form = data['across_cities'] travel_time = data['travel_time'] graph = get_graph() all_ways = list(dfs_paths(graph, from_city.id, to_city.id)) if len(all_ways) == 0: messages.error(request, 'There is no routes') return render(request, 'routes/home.html', {'form': form}) if across_cities_form: across_cities = [city.id for city in across_cities_form] right_ways = [] for way in all_ways: if all(point in way for point in across_cities): right_ways.append(way) if not right_ways: messages.error(request, 'The route through these cities is impossible') return render(request, 'routes/home.html', {'form': form}) else: right_ways = all_ways trains = [] for route in right_ways: tmp = {'trains': []} total_time = 0 for i in range(len(route) - 1): qs = Train.objects.filter(from_city=route[i], to_city=route[i + 1]) qs = qs.order_by('travel_time').first() total_time += qs.travel_time tmp['trains'].append(qs) tmp['total_time'] = total_time if total_time <= int(travel_time): tmp['from_city'] = from_city tmp['to_city'] = to_city trains.append(tmp) if not trains: … -
Wagtail Template does not contain request.user
I have configured wagtail 2.9, Everything works preety fine. But I couldn't able to access request.user or request.site from the wagtail template(home_page.html). My model is configured as below. class HomePage(Page): template = "home/home_page.html" editors_note = models.CharField(max_length=100, blank=False, null=True) editors_text = RichTextField(blank=False, null=False, default='Enter Text here', features=['h1','h2', 'h3', 'bold', 'italic', 'link']) editors_name = models.CharField(max_length=100, blank=False, null=True) content_panels = Page.content_panels + [ MultiFieldPanel( [FieldPanel('editors_note'), FieldPanel('editors_text'), FieldPanel('editors_name')], heading='Editors Note' )] I tried creating one more normal django page using the below view function. def landing(request): request.session['uid'] = user_id user = LDAPBackend().populate_user(uid) request.user = user return render(request, 'home/landing.html') Here in the landing page, I can able to access request.user and request.session.sso_id. Do I need to configure something for the request to access in the template, I have tried redirecting from landing.html to home_page.html still its not available. -
bachground Scheduler of django-apscheduler does not run the jobs
I want to send data to the database using django-apscheduler in the background but when I use Background Scheduler , the Scheduler does not run my jobs. The job is here : def my_job(): time = timezone.now().strftime('%X') print("It's now %s" % time) The Scheduler for running the job is : class Command(BaseCommand): help = "Runs apscheduler." def handle(self, *args, **options): scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( my_job, trigger=CronTrigger(second="*/10"), # Every 10 seconds id="my_job", max_instances=1, replace_existing=True, ) logger.info("Added job 'my_job'.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!") (I've just used a simple job to test Scheduler.) When I run python manage.py tasks the job is added in django jobs but it does not appear in execution part of Django Admin.what is wrong? Any help would be appreciated. -
Django channels image saving, TextField or ImageField
Chat app using django channels I am using websockets to send base64 encoded string to the server, the base64 encoded string could be saved in TextField or saved in ImageField by decoding using base64 library, which method is preferred, why? -
Django annotate if field exists in second model ArrayField
I have the following 2 models. I'm trying to annotate the DeliveryRegionLog queryset with a boolean that indicates whether a DeliveryRegion exists with the postal code in the ArrayField postal_codes. class DeliveryRegion(models.Model): name = models.CharField(max_length=255) postal_codes = ArrayField( models.CharField(max_length=255, blank=True), blank=True, default=list, help_text='Comma separated list of postal codes.' ) class DeliveryRegionLog(models.Model): postal_code = models.CharField(max_length=64) checks = models.PositiveIntegerField( default=1, help_text='The number of times someone has checked if ' 'this postal code exists in a delivery region.' ) I've tried the following but it doesn't work and I can't figure out why. from django.db.models import Exists, OuterRef postal_code = 'A1A' DeliveryRegion.objects.create(postal_codes=[postal_code]) DeliveryRegionLog.objects.create(postal_code=postal_code) DeliveryRegionLog.objects.annotate( region_exists=Exists( DeliveryRegion.objects.filter(postal_codes__contains=[OuterRef('postal_code')]) ) )[0].region_exists # False DeliveryRegionLog.objects.annotate( region_exists=Exists( DeliveryRegion.objects.filter(postal_codes__contains=[postal_code]) ) )[0].region_exists # True -
Django Rest Framework: how to add total sum to ListAPIView?
I want to add total sum of field to the response. What is the best way to do it? -
Remove trailing slashes in Django URLs
Is there any way of stripping all trailing URLs in Django and redirecting them to the non slashed URL. i.e. If I go to /home/ I want to be redirected to /home. Currently I get a 404 as the page "does not exist". There was one piece of middleware I found which is outdated. Called Django-unslashed. Would this be a case of adding something to the urlconf, or writing custom middleware? -
Read multiple records as one in Django
everyone, I am in the middle of a grouping of rows of a table Relationship with the same name as one. example- the table will look like Parent_name .... Childern_name A Mittal ........ Children 1 A Mittal ........ Children 2 A Mittal ........ Children 3 B Mittal .........children 1 B Mittal .........children 2 Now I created an HTML where I want to see only A Mittal B Mittal For which I have to define in views - parentnames= Relationship.objects.distinct(Parent_name) But it's not working kindly help. Is there any other way also to do it? -
Creating user profile on successful registration DJANGO
Imm trying to create a user profile for users on successful registration, but facing some issues, can't seem to figure out the problem. On successful registration it doesn't create any profile for user, but i was able to manual create profile admin page. Here's what i tried: Models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpeg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required() def profile(request): return render(request, 'users/profile.html', context) Apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals profile.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ … -
how to financial settlements with partners in django oscar?
I'm trying to develop an eCommerce website by Django-oscar. I have multi partners in my project and I don't know how to financial settlements (check out) with partners in Django oscar? can you help me? Do you know how oscar handle that? -
Downloading a file via Axios from Django
I'm trying to get filename from blob request using Axios and Django. Django's view: with open(full_file_path, 'rb') as f: response = HttpResponse(f, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') file_expr = "filename*=utf-8''{}".format(quote(file_name_with_ext)) response['Content-Disposition'] = 'attachment; {}'.format(file_expr) return response Frontend: axios .request({ url, method, responseType: 'blob', }) .then(({ data }) => { console.log(data); const downloadUrl = window.URL.createObjectURL(new Blob([data])); const link = document.createElement('a'); link.href = downloadUrl; link.setAttribute('download', 'file.xlsx'); document.body.appendChild(link); link.click(); link.remove(); }); But parameter 'data' doesn't contain headers to allow me to get filename. Is there any solution? -
Django Rest Framework: obtain user details and permissions with token login
My (Angular) frontend performs jwt login to the Django Rest Framework backend through the provided jwt_views.TokenObtainPairView class. However, this returns only access and refresh tokens, and I'd actually like to get more, such as username and the permissions the user has (so that the frontend can hide or disable any features the user can't use anyway). What would be the best solution to achieve this? Write my own token-generating view? Subclass the existing view and overwrite the serializer with one that fetches user information? Use a different method to transfer permissions or to log in? The level of 'magic' that happens in Django confuses me as to what parameters and values I can set and overwrite. -
pandas read_excel from open file throws UnicodeDecodeError
I am trying to read data from excel to pandas. The file I get comes from api and is not saved (the access to the file needs special permissions, so I don't want to save it). When I try to read excel from file with open('path_to_file') as file: re = pd.read_excel(file) I get the error UnicodeDecodeError: 'utf-8' codec can't decode byte 0x98 in position 10: invalid start byte When I input path in palce of file everythng works fine re = pd.read_excel('path-to-exactly-the-same-file') Is there a way to read excel by pandas without saving it and inputting path? Thanks in advance! -
List of checkbox Django ModelForm
I'm new to Django and I'm creating a very simple form, here it is I would like to have a radio select checkbox (instead of a choice list like I have now) Something like this I've tried to put some widget=forms.RadioSelect in my model but it seems we can't do that here Do you know how I could do this ? Here is my code : models.py from django.db import models from django import forms class Post(models.Model): SAMPLE_CHOICES =( (0, "Very satisfied"), (1, "satisfied"), (2, "neutral"), (3, "not very satisfied"), (4, "not satisfied at all"), ) q1 = models.IntegerField(choices = SAMPLE_CHOICES, verbose_name=u"cleanliness of the premises") q2 = models.IntegerField(choices = SAMPLE_CHOICES, verbose_name=u"quality of services") urls.py from django.urls import path from . import views urlpatterns = [ path('post/new/', views.post_new, name='post_new'), ] views.py from .forms import PostForm from.models import Post from django.shortcuts import render def post_new(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST) print(form.is_valid()) # some debug print(form) if form.is_valid(): form.save() print(Post.objects.all()[-1].q1) # I print the form i just saved for debug purpuse return render(request, 'blog/post_edit.html', {'form': form}) forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('q1', 'q2') base.html {% … -
django.db.utils.IntegrityError: (1062, "Duplicate entry '15-delete_comment' for key 'auth_permission_content_type_id_codename_01ab375a_uniq'"
I wanna change my database from Sqlite to MySql. I get this error every time I run the "manage.py migrate" command. I did this when I had stored information in the previous database(It may be related to this?) I must also say that I use "django-comment-dab" to implement Comment System. Why is there so much trouble changing the database? error: File "/home/amirhos2/virtualenv/weblog/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/amirhos2/virtualenv/weblog/3.7/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1062, "Duplicate entry '15-delete_comment' for key 'auth_permission_content_type_id_codename_01ab375a_uniq'") Also comment.model: class Comment(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, blank=True, null=True,verbose_name='کاربر') email = models.EmailField(blank=True, verbose_name='ایمیل') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, verbose_name='نوع') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') content = models.TextField(verbose_name='متن نظر') urlhash = models.CharField( max_length=50, unique=True, editable=False, verbose_name='آدرس' ) posted = models.DateTimeField(default=timezone.now, editable=False, verbose_name='پست شده') edited = models.DateTimeField(auto_now=True,verbose_name='ویرایش شده') objects = CommentManager() class Meta: verbose_name = 'نظر' verbose_name_plural = 'نظرات' ordering = ['-posted', ] def __str__(self): if not self.parent: return f' نظر از طرف {self.user}: {self.content[:20]}' else: return f'پاسخ از طرف {self.user}: {self.content[:20]}' def __repr__(self): return self.__str__() def to_dict(self): return { 'user': self.user, 'content': self.content, 'email': self.email, 'posted': str(self.posted), 'app_name': self.content_type.app_label, 'model_name': self.content_type.model, 'model_id': self.object_id, 'parent': getattr(self.parent, 'id', None) } def _get_reaction_count(self, … -
How to insert Primary key uisng Django Models?
i have set Primary key in my Django Models and but When i am inserting data into MongoDB database ,the primary key is not inserted.by default Django is inseting primary key but in my case its not.i Don't know what i am Doing Wrong Here.i am using below code My Model.py class CategoryModel(models.Model): id = models.AutoField(primary_key=True) #if i don't use this line,django should insert primary by default.i my other app its inserting by default category_name = models.CharField(max_length=255) when i insert data into my CategoryModel,the primary key is not inserted.i am using Following code to insert data Views.py CategoryModel.objects.create( category_name =request.POST['category_name'] ) Here,category_name is inserted but Primary key is not inserted.I don't know what is the issue.i Will be thankful if any one can help me with this issue. -
Django flash messages showing only on the django admin page and not on the template
I have a login form and just want to display a confirmation message as soon as the user logs in. The message is being displayed, but it is displayed on the django admin page and not on the template(the web page visible to the user). I have checked almost everything like importing messages from django.contrib, checking the installed apps list, middleware list, context_processors. I don't know where am I going wrong or what am I missing. Please help! My views.py function def login_method(request): loginusername = request.POST['loginusername'] loginpass = request.POST['loginpass'] user = authenticate(username=loginusername, password=loginpass) if user is not None: auth_login(request, user) messages.success(request, "Successfully Logged In!") return redirect("appHome") else: messages.error(request, "Invalid Credentials, Please try again!") return redirect("home")