Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redis on Heroku not recognizing Django celery migrations
I have a basic Django app deployed on Heroku with a Redis addon and postgres addon, and my tasks are running fine locally. However, on the deployed app, the worker is not recognizing the celery tables/migrations. I've checked that all migrations have been run on the deployed app (heroku run python3 ./manage.py showmigrations -a {my-app}). My Procfile command: celery -A my_app worker --beat -S django -l info Running this command locally works fine and correctly receives the tasks. I have the DATABASE_URL env variable on heroku set from the postgres addon, and additionally I have added POSTGRES_USER, POSTGRES_DB, and POSTGRES_PASSWORD env variables for the same postgres database. The REDIS_URL is set as well as an env variable, from the Redis addon. Here are the logs from my heroku app's worker, which is successfully connected to redis: [2022-02-20 03:29:59,235: INFO/MainProcess] Connected to redis://:**@ec2-3-224-115-109.compute-1.amazonaws.com:12849// 2022-02-20T03:29:59.250151+00:00 app[worker.1]: [2022-02-20 03:29:59,249: INFO/Beat] beat: Starting... 2022-02-20T03:29:59.257880+00:00 app[worker.1]: [2022-02-20 03:29:59,257: INFO/MainProcess] mingle: searching for neighbors 2022-02-20T03:29:59.299601+00:00 app[worker.1]: [2022-02-20 03:29:59,297: ERROR/Beat] Process Beat 2022-02-20T03:29:59.299605+00:00 app[worker.1]: Traceback (most recent call last): 2022-02-20T03:29:59.299607+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute 2022-02-20T03:29:59.299607+00:00 app[worker.1]: return self.cursor.execute(sql, params) 2022-02-20T03:29:59.299608+00:00 app[worker.1]: psycopg2.errors.UndefinedTable: relation "django_celery_beat_periodictask" does not exist 2022-02-20T03:29:59.299608+00:00 app[worker.1]: LINE 1: ...ango_celery_beat_periodictask"."description" FROM "django_ce... … -
How can i Use Django with Docker?
So I have a basic django blog application. Which i want to dockerise into django. And one more thing. I am writing my question here because there are live people to answer. -
Bokeh: Generate graph server side, update graph from JS client side (change data source, axes ...)
I just took Bokeh for a spin on a Django site. Lot of fine tutorials out there and really easy to get a quick example running. For example, I have a Django view that offers something like: ... # This is part of a broader Django view, simply adding a graph to it. # Fetch the x and y data for a histogram using a custom function. # It takes a queryset, a field in that queryset and returns, two lists one # containing the unique values that some field took on and the second containing # the count of times it took on that value. (values, frequency) = FrequencyData(some_queryset, "some field") p = figure(height=350, x_axis_label="Count of Players", y_axis_label="Number of Events", background_fill_alpha=0, border_fill_alpha=0, tools="pan,wheel_zoom,box_zoom,save,reset") p.xaxis.ticker = values p.yaxis.ticker = list(range(max(frequency) + 1)) p.toolbar.logo = None p.vbar(x=values, top=frequency, width=0.9) p.y_range.start = 0 graph_script, graph_div = components(p) context.update({"graph_script": graph_script,"graph_div": graph_div}) ... Then in the Django template I simply have: {{ graph_div | safe }} {{ graph_script| safe }} And I have a lovely histogram of data that is otherwise presented in a table on that view. I like it. Now the same view, like many, has a pile of settings for filtering … -
How to get list of all objects associated with a foreign key in Django
Not super experienced with Django so I apologize if this is trivial. Say I had a category instance and I wanted to get access to all of the content objects that I have previously added to my foreign key. How would I do so? class Organization(models.Model): id = models.CharField(primary_key=True, max_length=200, default=uuid4, editable=False, unique=True) name=models.CharField(max_length=200,unique=True) phoneNumber=models.CharField(max_length=20) logo=models.CharField(max_length=100000) # storing this as base 64 encoded location=models.CharField(max_length=200) class Category(models.Model): categoryName=models.CharField(max_length=300, unique=True, primary_key=True) associatedOrganizations=models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='associatedOrgs',null=True,blank=True) associatedContent=models.ForeignKey(Content, on_delete=models.CASCADE,related_name='associatedContent',null=True,blank=True) associatedMeetingNotices=models.ForeignKey(MeetingNotice,on_delete=models.CASCADE,related_name='associatedMeetingNotices',null=True,blank=True) For example: say I had the following healthcareCategory=models.Category.objects.get(pk="healthcare") and I wanted to access all Organizations related to healthcare, what should I do? This? healthcareCategory.associatedOrganizations.all() -
Django query: Calculate average monthly spend per user
Given a Django model which stores all transactions made by users, how can I create a query that returns the average monthly spend for each user? My current solution queries all the transactions then manually calculates the averages for each user however I am aware that there is a more pythonic way to do this using Django annotations but unsure how to write it. models.py Class Transactions(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey('User', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=100, decimal_places=2, blank=True, null=True) date = models.DateField() -
Positioning Django objects, with template for loop tags *Struggling to replicate Instagram push and pop of photo location *
I am having difficulty positioning the photo location after a user posts a photo, where the (Purple Gameboy Photo) goes where the (Mansion Photo) is, and where the (American Football Player Photo) goes where the (Purple Gameboy Photo) is, just like Instagram's profile. Where the most recent go to the top left of the photos, and the last posted photos get pushed down to the bottom right The function checks the first iteration of the for loop and creates a row and column for the first photo, the American Football Player Phot is the first photo posted, then moves along until the fourth photo comes in. Rather than poping the oldest photo to a new row and pushing the newest photo to the front of the existing row. It keeps the location of the first photo and creates a new row for the latest photo. Profile_Page.html <!-- -----------------------------------------ALBUM SECTION---------------------------------------- --> <div class="album-section"> <h2>Albums</h2> {% for x in img %} {% if forloop.first %} <div class="row ">{% endif %} <div class="col-4 col-4 col-4" > <div class="text-center mt-2"> <a href="{% url 'single_page' x.id %}" ><img src="{{x.file.url}}" href="{% url 'single_page' x.id %}" height="100%" width="100%" class="myImg"></a> </div> </div> {% if forloop.counter|divisibleby:3 %} </div> <div … -
User oriented dynamic URL not loading - Django
I'm having this issue where I can register and login users but when I go to view the data (as the signed in user) nothing will load. I've been struggling with it quite a bit and just can't figure it out. When I look at the Django error page it shows it is pulling the correct user but won't show it. Dynamic URL per user issue - Django error page Here is the urls.py: from django.urls import path from.import views urlpatterns = [ path('',views.HomePage, name='HomePage'), path('category/<slug:slug>', views.CategoryPage, name='image-date'), path('<slug:slug_customer>/',views.Customer), Here is the models.py: from django.db import models from django.template.defaultfilters import slugify from django_resized import ResizedImageField from django.utils import timezone from uuid import uuid4 from django.urls import reverse class User(models.Model): user_name = models.CharField(max_length=100) #insert way to have user specific .csv link class Category(models.Model): title = models.CharField(null=True, blank=True, max_length=200) class Image(models.Model): description = models.TextField(null=True, blank=True) altText = models.TextField(null=True, blank=True) #ImageFields squareImage = ResizedImageField(size=[1000, 1000], crop=['middle', 'center'], default='default_square.jpg', upload_to='DB Pictures') #Related Fields category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) Here is my views.py: from django.shortcuts import render from .models import * # Create your views here. def HomePage(request): categories = Category.objects.all() context = {} context['categories'] = categories return render(request, 'HomePage.html', context) def CategoryPage(request): categories … -
Can We Implement Flask-JWT In Django?
1). Guys I need to implement jwt in my Django Rest Framework Application 2). but I want to implement jwt without a database like Flask https://pythonhosted.org/Flask-JWT/ like these. 3). Can You Please help me with this I like this flask jwt please help me with this. -
How Do I Convert This Function Based View To An UpdateView?
I've been staring at code for too long...but I can't figure this out for the life of me... I am trying to convert a function based view to a class based view....I've done it with the CreateView but the UpdateView is giving me grief. It won't take my update....I can get the view to take my update...but it doesn't save it....I don't get it... Here's my function based view... def update_task_update_view(request, pk): task = Task.objects.get(id=pk) form = TaskForm(request.POST or None, instance=task) if request.method == "POST": if form.is_valid(): form.save() return redirect("MyTasks:task_detail", pk=task.id) context = { "form": form, "task": task } return render(request, "partials/task_form.html", context) And here was my attempt at a Class Based View.... class UpdateTaskUpdateView(LoginRequiredMixin,UpdateView): model = Task form_class = TaskForm template_name = 'partials/task_form.html' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): task = form.save() task.save() return redirect("MyTasks:task_detail", pk=task.id) else: return render(request, "partials/task_form.html", { "form":form }) This function based view is working fine...no issues with it. Thanks in advance for any thoughts. -
How to custom save login information in django
I am creating an app where I am dealing with an external REST API, I am sending my login credentials along with JWT token if they are correct I get a success status along with phone number and id, Now I dont know how to save this data to set persmissions to disaplay pages, like in normal app we sigply use login(request, user) to save the user but here we dont have database. Now I want to show some of the pages if the user is authenticated.I tried using reuqest.session['user_id] but deleting the session when user clicks on logout but this does't seems to be a good idea. -
How can I include all my html files in my base.html file in django?
I have a couple of html files in my django project including a base.html file, navbar.html, footer.html, etc. I have included the navbar and footer files in the base file and extended the base file to a home.html file which happens to be my main page. I recently created a courses.html file and would like this page to also be in the main page. I understand I can include it like I did with navbar and footer, but that would mean the courses.html file will be shown everywhere the base file has been extended to, and I don't want this. How can I do this? -
Installing python from source in virtual environment (Ubuntu)
I have a Django project that I want to integrate with Apache. Django development was done with Python3.10 (which is installed in the virtual environment). OS is Ubuntu. I now learned that mod_wsgi and Python3.10 don't play well together (issue link from mod_wsgi project). Sounds like Python 3.10.2 will fix it, but it's not yet available on deadsnakes (which is how I installed it in the virtual environment). I think I have 3 options Try to downgrade to Python 3.8 (I've not done it before and I am worried I'll break other dependencies) Wait for compiled 3.10.2 to be available (not sure how long it takes - can't afford to miss my deadlines) Compile Python from source My question is about 3. I compiled it for the OS, but don't know how to install it within the virtual environment (I tried to look at the make file, but couldn't figure it out). I can use some help on how to install Python3.10.2 within the virtual environment. Or I'll take any advice on how I can move forward (could be a short term solution that would work in production - followed by a longer term solution eventually). -
How can I use my own styling and html code on django forms?
I am quite new to django, and I've been struggling with the concept of form styling in django. I do not want to use any other styling aside my own styling for the forms. How do I do this? By the way, this is my code below. <form id="contact" action="" method="post"> <div class="row"> <div class="col-md-6"> <fieldset> <input name="name" type="text" class="form-control" id="name" placeholder="Your Name" required=""> </fieldset> </div> <div class="col-md-6"> <fieldset> <input name="email" type="text" class="form-control" id="email" placeholder="Your Email" required=""> </fieldset> </div> <div class="col-md-12"> <fieldset> <textarea name="message" rows="6" class="form-control" id="message" placeholder="Your message..." required=""></textarea> </fieldset> </div> <div class="col-md-12"> <fieldset> <button type="submit" id="form-submit" class="button">Send Message Now</button> </fieldset> </div> </div> </form> -
Accessing Database from other location
For my job interview, I got assignment to create CRUD with Django and Postgresql. I created database locally and finished my assignment. Now I have to upload my code to github. The problem is, they asked for some exampled for CRUD. Developer that is reviewing my code obviously can't access my local DB. What can I do to solve this issue? Do I have to upload my DB to cloud (if so what is the best way to do that)? Or is there any other way to resolve this? Thanks in advance -
I need your help about my website structure which written with Django
I need your help about my website structure which written with Django. My website has a posting part. When I am in main page, I want to go post page if only you are authenticated. Thats works now but when I write post part as url https://starofgeeks.com/post it can go directly to the post part without authentication. Can you recommend any structure for this situtation. Main page is starofgeeks -
How to test update form in django
I have a issue in my django project. I have a custom user model and I created update form and register form with ModelForm class for the user model. I wrote a unit test with TestCase class for to test the form but I'm getting __init__() got an unexpected keyword argument 'instance' error message. I couldn't find any solution for the issue. Can anyone help me solve the issue? Form: class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ('email', 'username', 'first_name', 'last_name') username = forms.CharField( widget=forms.TextInput( attrs={ } ) ) email = forms.EmailField( widget=forms.EmailInput( attrs={ } ) ) first_name = forms.CharField( widget=forms.TextInput( attrs={ } ) ) last_name = forms.CharField( widget=forms.TextInput( attrs={ } ) ) def clean_username(self): username = self.cleaned_data.get('username').lower() try: user = User.objects.exclude(pk=self.instance.pk).get(username=username) except User.DoesNotExist: return username else: raise forms.ValidationError(f"Sorry but {username} was taken already") def clean_email(self): email = self.cleaned_data.get('email').lower() try: user = User.objects.exclude() except User.DoesNotExist: return email else: raise forms.ValidationError(f"Sorry but {email} was taken already") def clean_first_name(self): first_name = self.cleaned_data.get('first_name') first_name = normalize_name(first_name) return first_name def clean_last_name(self): last_name = self.cleaned_data.get('last_name') last_name = normalize_name(last_name) return last_name My unit test: def updateUser(self): user = UserRegisterForm(data) if user.is_valid(): user = user.save() print(user.username) username = 'user1' email = 'user1@gmail.com' first_name = 'user' … -
Using Google Maps API in Django
New to Django. I've been making a web application using Django to show nearby restaurants when the user enters the address. I have all the necessary Google Maps API keys but don't know how to apply them to my code. Can someone help me with this? -
Postgre+Docker+Django OperationalError
I've got an issue with connecting PostgreSQL with Django using Docker. Error: web_1 | django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" If I don't use Docker (just runserver command in prompt) it looks as it should, no errors. In another project Docker works correctly with this config. My docker-compose.yml: version: '3.8' services: web: build: . command: python bookstore/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db:db db: image: postgres:14 environment: - POSTGRES_USER= postgres - POSTGRES_PASSWORD= postgres - POSTGRES_DB= postgres My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } -
python django flexible access control system
I have a need for a flexible system of rights, that is, there is some object and only some users have access to it, they may also have different levels of rights in this object, This is a Backend, that is, a request comes from an authorized user and the server responds with all the objects that this user has access to, there were attempts with Django Rest Framework, but it is very difficult to understand and I did not find examples with Django Access, it is not mandatory to use Django, you can do anything that can solve this problem (Python only) Please tell me which way to look and figure it out! -
Deleting object from the url
I am trying to override delete action in my CategoryViewSet, the build in delete action taked the id of the category DELETE ..category/1/, but I want it to delete by the slug argument DELETE ..category/movie/. I can not figure out how can I withdraw slug field from the url (*args) models.py class Category(models.Model): name = models.CharField( max_length=255, verbose_name='Category Name' ) slug = models.SlugField( unique=True, verbose_name='Slug Name', max_length=50 ) serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'slug') views.py class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer def destroy(self, request, *args, **kwargs): try: slug = args[0] delete_category = Category.objects.filter(slug=slug) self.perform_destroy(delete_category) except Http404: pass return Response(status=status.HTTP_204_NO_CONTENT) urls.py router_v1.register( r'categories', CategoryViewSet ) urlpatterns = [ path('', include(router_v1.urls)) ] -
how to show manytomany field data in json format - django
I'm trying to show manytomany data in json format(without using serializer), here is my models.py class CustomerInvoice(models.Model): customer = models.CharField(max_length=50) items_model = models.ManyToManyField(Item,through='InvoiceItem') created_at = models.DateTimeField(auto_now_add=True) class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') quantity = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=2) is it possible to make a look up base on many to many data? something like this : Q(items_model__icontains=query_search) ,and also how to return the M2M data into a json format using values() and json.dumps please? this returns the ID Values('items_model') and this dont work Values('items_model__all') and here is my views.py def invoices_all_lists(request): if request.is_ajax(): query_search = request.GET.get('filter') if query_search: all_item_qs = CustomerInvoice.objects.all() a = [] for i in all_item_qs.items_model.all(): a.append(i.item.name) invoices = CustomerInvoice.objects.annotate( total=Sum((F('invoice__quantity') * F('invoice__price')),output_field=DecimalField(decimal_places=2,max_digits=20)) ).filter( Q(id__icontains=query_search) | Q(seller__username__icontains=query_search) | Q(customer__icontains=query_search)).values( 'id','seller__username','customer','total','created_at','items_model').order_by('-id') else: all_item_qs = CustomerInvoice.objects.all() a = [] for data in all_item_qs: for i in data.items_model.all(): a.append(i.item.name) invoices = CustomerInvoice.objects.annotate( total=Sum((F('invoice__quantity') * F('invoice__price')) ,output_field=DecimalField(decimal_places=2,max_digits=20)) ).values( 'id','seller__username','customer','total','created_at','items_model').order_by('-id') start_from = 0 if request.GET.get('start'): start_from = int(request.GET.get('start')) limit = 10 if request.GET.get('limit'): limit = int(request.GET.get('limit')) data_lists = [] for index,value in enumerate(invoices[start_from:start_from+limit],start_from): value['counter'] = index+1 data_lists.append(value) data = { 'objects':data_lists, 'length':invoices.count(), } return HttpResponse(json.dumps(data, indent=4, sort_keys=True, default=str),'application/json') else: return redirect('invoiceapp:list-all-invoice') can i add this part of the code into the … -
Display items grouped in month together using django regroup
I have a model with following fields examname | month a1 Jan a2 Jan a3 Jan b1 Feb b2 March b3 March I want to display exams in each month grouped in months example Jan : a1 a2 a3 Feb : b1 March: b2 b3 I am using the following queryset def getallexams(request): exams = exam.objects.annotate(month_total=Count('month')).order_by('month') print(exams) context={ "exams" : exams, } return render(request, 'exams/index.html',context) Below is the code I am using to render the template: {% regroup exams by month as month_list %} <div class="accordion" > {% for month in month_list %} {{month.grouper }} # I am not sure how to loop through this month to display each exam {% endfor %} -
django channels realtime total notification
I need realtime total number of notification using django channels. signals.py @receiver(post_save, sender=Notification) def create_notification(sender, instance, created, **kwargs): if created: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'realtime_order', { 'type': 'notification_count', 'text': Notification.objects.all().count() } ) consumers.py class NotificationConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_group_name = None def connect(self): self.room_group_name = f'realtime_order' self.accept() # join the room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name, ) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name, ) def receive(self, text_data=None, bytes_data=None): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'notification_count', 'message': Notification.objects.all().count(), } ) def notification_count(self, event): self.send(text_data=json.dumps(event)) Dont know is it the correct procedure. And code is not working. -
DJANGO cant navigate to page using a hyperlink but typing page address works fine
doing a simple django project with 2 apps one for blogs and the other is for users both work fine but i cant navigate using the hyperlink in this page <p> <a href="{% url 'learning_logs:home' %}">Home</a> <a href="{% url 'learning_logs:topics' %}">Topics</a> {% if user.is_authenticated %} Hello, {{ user.username }}. <a href="{% url 'users:logout' %}">logout</a> {% else %} <a href="{% url 'users:login' }">login</a> {% endif %} urls.py in users from django.urls import URLPattern, path from django.contrib.auth.views import LoginView from . import views app_name = 'users' urlpatterns = [ path('login/', LoginView.as_view(template_name='login.html'), name='login'), path('logout/', views.logout_view, name='logout'), ] main urls of project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls', namespace='learning_logs')), path('users/', include('users.urls', namespace='users')), ] error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%7B%25%20url%20'users:login'%20%7D Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ [name='home'] topics [name='topics'] topics/<topic_id> [name='topic'] new_topic [name='new_topic'] new_entry/<topic_id> [name='new_entry'] edit_entry/<entry_id> [name='edit_entry'] users/ The current path, {% url 'users:login' }, didn’t match any of these. it shows the page if i type /users/login/ in the address bar -
Django: how to get the value inside a querydict?
I have the following querydict: <QueryDict: {'data_dict[user_id]': ['5'], 'data_dict[location]': ['Library'], 'data_dict[item_sold]': ['book']}> I want to get the value by using the key: i.e (x = data_dict.get('user_id') How can I do that? everytime I try to access the querydict it throws errors.