Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not dispatching the request to correct view function
I am new to Django. And I am building an ecommerce website. I have these 2 urls. path('', views.cart, name='cart'), path('delete/<int:order_id>', views.cart, name='remove') These are 2 functions in my views def cart(request): def remove(request, order_id): When ever I try to make request to the remove view it gives me this error. TypeError: cart() got an unexpected keyword argument 'order_id' http://localhost:8000/cart/delete/96 What I understand from this is that it is calling the cart method instead of remove. The cart method is working fine. I am calling this remove method with Ajax. $.ajax({ type: 'GET', url: `delete/${order_id}`, success: function(){ console.log("helloo"); }}); I think i am missing some thing very basic here. Any help will be much appreciated. Thanks. -
Django google calendar - timeout
I've just added a view that adds an event to user's google calendar and it made my application throw 504 Gateway Time-out error. Here are some code pieces: function that adds an event to google calendar def add_event_to_calendar(request, pk): if request.user.is_authenticated: obj, created = EventUser.objects.get_or_create(event_id=pk, user=request.user) if created: SCOPES = 'https://www.googleapis.com/auth/calendar' store = file.Storage('token_' + str(request.user.id) + '.json') creds = store.get() event = Event.objects.get(pk=pk) later = event.event_time.replace(hour=event.event_time.hour + 1) if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) event_to_add = { "summary": str(event.name), "description": event.description, "start": { "dateTime": event.event_date.strftime('%Y-%m-%dT') + event.event_time.strftime('%H:%M:%S') + 'Z', }, "end": { "dateTime": event.event_date.strftime('%Y-%m-%dT') + later.strftime('%H:%M:%S') + 'Z', } } event_to_add = json.dumps(event_to_add, indent=4, sort_keys=True, default=str) service.events().insert(calendarId='primary', body=json.loads(event_to_add)).execute() return redirect(reverse('news:list')) Tokens for each user are created in the directory containing the view, with file name pattern: "token_" Nginx configuration: server { server_name www.domain_name.com domain_name.com; return 301 https://domain_name.com$request_uri; } server { listen 443 ssl; ssl_certificate /etc/letsencrypt/live/domain_name.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain_name.com/privkey.pem; # managed by Certbot server_name www.domain_name.com; return 301 https://domain_name.com$request_uri; } server { server_name domain_name.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/admin/project_name; } location / { proxy_pass http://0.0.0.0:8000; proxy_set_header X-Forwarded-For … -
Template does not exist django flatpages
Made a cms project in django, but its not loading my default template for flatpages, attached are the images. Thanks INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware' ] -
How do I use a template from one app in another app
Currently trying to make a social application. I created two apps Main and posts. My post app will handle all functionality for creating, deleting a post, list of posts. My Main app is my homepage which would display all posts, for example similar to a facebook's homepage. Main app currently authenticates users and what not. I created views and template for my posts app and I now want to include it on the Main's app homepage. Not sure how to go out about doing this. Not asking for anyone to write up the code but at least give a structure on how to achieve this. Basic Structure of the app --Main_app --_views.py --templates --home.html --posts_app --_views.py --templates --posts.html One of the files my posts_app views contains currently is. def posts_list(request): #return HttpResponse("<h1> List a posts. </h1>") render(requests, "posts.html", {}) templates/posts.html contains this file. <!DOCTYPE html> <html lang="en"> <body> <h1>Posts template is working</h1> </body> </html> And In my main_app templates/html {% if user.is_authenticated %} <h1>Homepage</h1> <!-- Posts template --> {% include "posts/templates/posts.html" %} {% endif %} It made sense to me at the time to just import the template from the posts app to the main app and it would work. … -
Is it possible to increment a value with F in a json field in django?
Is it possible to increment a value with F in a json field in django? I have an object that contains a json field and I have some keys in it. Is it possible to increment the key value inside a json used F? Thank you for all. credits = Company.objects.filter().first() credits.meta_data = F('meta_data')['credits'] + 1 credits.save() -
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['todos\\/detail\\/(?P<id>[0-9]+)\\/$']
I m trying to build a todo app in django. Having a problem while link to detail page unable to link up to the page. here is my code. **todos/index.html:** {% if todo %} <ul> {% for todos in todo %} <li><a href="{% url 'todos:detail' todo.id %}">{{ todos.text }}</a></li> {% endfor %} </ul> {% else %} <p>No Todo list are available.</p> {% endif %} view.py: from django.shortcuts import render from django.http import HttpResponse from .models import Todo # Create your views here. def index(request): todo =Todo.objects.all() context={'todo':todo} return render(request, 'todos/index.html',context) def detail(request,id): todo =Todo.objects.get(id=id) context={'todo':todo} return render(request, 'todos/detail.html',context) todos/url.py: app_name ="todos" urlpatterns = [ path('', views.index, name='index'), path('detail/<int:id>/', views.detail, name='detail'), ] **I have to actually click on the to activate the link: {{ todos.text }}. it works but it did not take me to the detail page** -
Django with mySQL
I have successfully set up and used Django with MySQL on my local machine, but now if I put my project on say GitHub what should the requirements be for any other person to be able to run it? I am asking this because my project uses a database that I have stored in my local machine and while uploading the project on GitHub I have not uploaded the database. in sqlite3 there is a database file inside the project itself but this does not happen for MySQL whose database is stored in a different location. I mean Django accesses the database from a different location(var/lib/MySQL) and when I try to copy the database from there to the project folder and specify its location in settings.py, I get an access denied error. So how can I solve this? -
I don't know why form doesn't show up on my page
I'm trying to make Order registration in my shop app, and everything work when I'm trying to make and save Order in my panel admin but problem is with ordering on page, form which I made dont want to show up on page order.html {%extends 'shop/base.html'%} {%load staticfiles%} {%block title%} Order {%endblock%} {% block content %} <form class= 'form_order' method="post"> Zamówienie: {% csrf_token %} {{ form }} <input type="submit" value="złóż zamówienie"> </form> {% endblock %} view.py from django.shortcuts import render from .forms import CreateOrderForm from .models import OrderItem from cart.cart import Cart def Order_view(request): cart=Cart(request) if request.method== 'POST': form=CreateOrderForm(request.POST) if form.is_valid: order= form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity'] ) cart.clear() return render(request, 'order/created_order.html', {order:'order'}) else: form=CreateOrderForm() return render(request, 'order/order.html', {cart:'cart', form: 'form' }) forms.py from django.forms import ModelForm from .models import Order class CreateOrderForm(ModelForm): class Meta: model=Order fields=['firstname', 'lastname', 'address', 'postal_code', 'city'] -
Error: Not all arguments converted during bytes formatting in Django backend with MySQL
I have a raw query like this: sql = 'SELECT * FROM foo_filters' with connection.cursor() as con: con.execute(sql, view) #this works fine filters = con.fetchall() But when I try this: product = 'foo' view = tuple(product + '_filters') sql = 'SELECT * FROM %s' with connection.cursor() as con: con.execute(sql, view) #this doesn't work filters = con.fetchall() I get this error: Error: Not all arguments converted during bytes formatting in Django backend with MySQL What am I doing wrong? -
Django Jwt Authentication on API Routes
I am new to Python world, I have experience with Laravel Framework and I am planning to create a web site in Python Django Framework. My only concern is that is it possible to have web and api routes, both in Django Framework. As in Laravel I was able to secure api routes with jwt authentication and web routes with normal login process. Is it possible to do the same with Django or Not ? if yes, can someone provide me a tutorial with web and api url routes. Thanks, -
Send templates in mailchimp with my django application
I have a mailchimp account with templates in it. I am able to integrate this to my django application and I am able to read the templates data in JSON format. Now I want to email these templates within my django application but I did not find any documentation on how to get the html form of the template in mailchimp and send it to individual emails. Below is the code I used to get the templates information client = MailChimp(mc_api='API_Key', mc_user='user') clients = client.templates.all(get_all=False) for template in clients["templates"]: print(template["name"]) -
Many DB query for string representation of model object
I have this models: class Country(models.Model): name = models.CharField(max_length=250) status = models.IntegerField(choices=STATUS, default=2) def __str__(self): return str(self.name) class City(models.Model): name = models.CharField(max_length=250) country = models.ForeignKey(Country, default=None) def __str__(self): return str(self.name) class Airport(models.Model): name = models.CharField(max_length=250) city = models.ForeignKey(City, default=None, blank=True) def __str__(self): return "{0} - {1} - {2}".format(self.city, self.city.country, self.name) For string representation of Airport Django sends many requests to DB: 302.06 ms (591 queries including 586 similar and 586 duplicates ) Queries screenshot: How I can reduce queries count? -
Dealing with two kinds of user in Django
What is the simplest way to deal with two kinds of user in Django, say, Teacher and Student - so that, when Teacher log in she can see the button "Create a test" and the students cannot see it; cannot create a test? Thanks! -
Passing additional context into CBV
I'm having trouble passing some additional context into a CBV. When I pass 'userprofile' as context, it prevents any other context from successfully being passed into the view. My view started as this: class OrderDetail(LoginRequiredMixin, DetailView): model = Order def dispatch(self, request, *args, **kwargs): try: user_checkout = UserCheckout.objects.get(user=self.request.user) except: user_checkout = None if user_checkout: obj = self.get_object() if obj.user == user_checkout and user_checkout is not None: #checks to see if the user on the order instance ties to the user of the current request return super(OrderDetail, self).dispatch(request, *args, **kwargs) else: raise Http404 else: raise Http404 I then tried adding this def get_context_data(self, *args, **kwargs): context = super(OrderDetail, self).get_context_data(*args, **kwargs) userprofile = UserProfile.objects.get(user=self.request.user) context["userprofile"] = userprofile I don't get any errors. It's just that when the page loads, none of the values that should appear (based on context) show up. Thanks! -
I can't remove a package in Django app since it is stored in migrations files
I'm trying to remove ckeditor package in my Django app. I removed ckeditor in INSTALLED_APPS. Because of that, I can't run my Django app since ckeditor it throws ModuleNotFoundError: No module named 'ckeditor' in several migrations files, and one of the files looks like the below. import ckeditor_uploader.fields from django.db import migrations, models import imagekit.models.fields import modvisor.blogs.models class Migration(migrations.Migration): dependencies = [ ('blogs', '0003_auto_20181204_1456'), ] operations = [ migrations.AddField( model_name='article', name='headline_image', field=imagekit.models.fields.ProcessedImageField(blank=True, null=True, upload_to=modvisor.blogs.models.image_path), ), migrations.AddField( model_name='article', name='status', field=models.CharField(choices=[('inactive', 'Inactive'), ('active', 'Active')], default='inactive', max_length=20, verbose_name='Showing Status'), ), migrations.AlterField( model_name='article', name='sub_title', field=ckeditor_uploader.fields.RichTextUploadingField(blank=True, verbose_name='Sub Title'), ), migrations.AlterField( model_name='article', name='title', field=ckeditor_uploader.fields.RichTextUploadingField(), ), ] My Django app has a production DB and server in AWS. I've searched about deleting migrations files, and most of people say it depends, but not recommended especially when it has production DB. Without touching the migrations files, how can I resolve this issue? -
Pandas CSV to Django Response
I have a DataFrame generated from a database. How do I provide a response wherein it downloads a CSV? I've got a working version with csv.writer, below, but for obvious reasons, that is not a DataFrame. -
Django Azure upload file to blob storage
I've got an application that needs to upload a file to an Azure Blob Storage container. I've been trying for a very long time and followed every tutorial to no avail. I have installed the following: pip3 install django-storages[azure] Here is my settings.py file: DEFAULT_FILE_STORAGE = 'backend.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'backend.custom_azure.AzureStaticStorage' STATIC_LOCATION = "static" MEDIA_LOCATION = "http://{AZURE_ACCOUNT_NAME}.blob.core.windows.net/media" MEDIA_ROOT='http://{AZURE_ACCOUNT_NAME}.blob.core.windows.net' AZURE_ACCOUNT_NAME = '<mystorageaccount>' AZURE_ACCOUNT_KEY = '<my key here>' AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' AZURE_LOCATION=f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' Here is the .backend/custom_azure.py <- my customer storage class from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = '<mystorageaccount>' account_key = '<mykey>' azure_container = 'media' expiration_secs = None class AzureStaticStorage(AzureStorage): account_name = 'mystorageaccount' account_key = '<my key>' azure_container = 'static' expiration_secs = None Here is my .account/models.py: from django.db import models from django.urls import reverse from django.contrib.auth.models import User from billing.models import Subs from PIL import Image import phonenumbers from backend.custom_azure import AzureMediaStorage as AMS class MasterAccount(models.Model): image = models.ImageField(default='default.jpg', storage=AMS, upload_to='profile_pics') profile_pic = models.FileField(default='default.jpg', storage=AMS, upload_to='profile_pics') def __str__(self): return "MasterAccount Number: " + str(self.number) def save(self, *args ,**kwargs): super().save(*args ,**kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) I am running this in apache.(not runserver) PROBLEM: … -
bootstrap datetimepicker won't work with 12h format
When I set the following format on the DateTimePickerInput widget, I get this error: "format" : "MM/DD/YYYY hh:mm a", Form Validation Error that I receive "Enter a valid date/time." Where can I set a valid date/time format? Thanks! -
How to save files to a foreign key model in django
I am using a django model to save user uploaded images. I want each image to be stored in the productimage model that is a foreign key model to the product model which is a foreign key model to the user model. What I mean is: User -----> Product ------> Productimage I want to create a new instance of the productimage model but can't seem to figure out how to since it is a foreign key to another foreign key. I do not know how to target a foreign key within a foreign key to create. For example I've tried: request.user.product.productimage.create() request.user.product_set.productimage_set.create() request.user.product.productimage_set.create() Nothing seems to create a new instance of the productimage model. class product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=100, blank=True) product_price = models.CharField(max_length=30, blank=True) product_description = models.CharField(max_length=1000, blank=True) class productimage(models.Model): product = models.ForeignKey(product, on_delete=models.CASCADE) product_images = models.FileField(blank=True) def add(request): if request.method == "POST": product_title = request.POST.get("product_title") product_price = request.POST.get("product_price") product_description = request.POST.get("product_description") request.user.product_set.create(product_title = product_title,product_price =product_price, product_description = product_description,) for file in request.FILES.getlist("filepond"): product_images = file request.user.product_set.productimage_set.create()###trying to create a new instance of productimage model for each file return render(request,"main/add.html") -
Let users create a Django page through own dashboard
I am looking for a way where I can give users the option to create a certain child page with pre specified fields through my own back-end dashboard. So I would give them a certain group permission in which they can add one child page. However I don’t want them to go to Django admin for that. But just through a nice Bootstrap template I will use. Here they can fill in fields which will render on a webpage. How to achieve this? -
django.urls.exceptions.NoReverseMatch: Reverse for 'Professors' with arguments '(1, 5)' not found
I'm trying to filter my professor table to display the professors that correspond to a specific school and specific major, the parameters are showing up in the error message, I just don't understand why there is a error message at all. Views.py from django.http import HttpResponse from django.shortcuts import render from .models import professor, School, Major, School_Major def index(request): schools = School.objects.all() return render(request, 'locate/index.html', {'schools': schools}) # def Major(request, Major): # major_choice = professor.objects.filter(Major =Major) # return render(request, 'locate/major.html', {'major_choice': major_choice}) def Majors(request, school_pk): schools_majors_ids = [] major_after_filter = [] #Filter to a show the association of 1 schools majors school_choice = School_Major.objects.filter(school_id = school_pk) #Append each of the major id's to school_majors_ids list for store in school_choice: schools_majors_ids.append(store.major_id) #Filter majors names required for store in schools_majors_ids: name = Major.objects.get(id = store) major_after_filter.append(name) return render(request, 'locate/major.html', {'major_after_filter' : major_after_filter, 'school_pk' : school_pk}) def Professors(request, school_pk, major_pk): professors = professors.objects.filter(school_id = school_pk).filter(major_id = major_pk) return render(request, 'locate/professors', {'professors' : professors}) url.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path(' <int:school_pk>/', views.Majors, name='Major'), path(' <int:school_pk/<int:major_pk>/', views.Professors, name="Professors") ] majors.html <h3 id="test">{{school_pk}}</h3> <ul> {% for major in major_after_filter %} <li><a href="{% url 'Professors' school_pk major.id … -
Best way to query/display multi-joined data from using Django
I'm new to Django, a question on query/display of joined tables. I have a model setup with "managers" and "skills"...and a join table of "managerskills". ManagerSkills has foreign key links to both the "manager" table and the "skill" table. This is a many to many table. (managers have many skills, skills belong to different managers) I am looking to retrieve a list of managers, display them in a grid, and have a column for "skills", which would display a comma-separated list of skills associated with the manager. class Manager(models.Model): title = models.CharField(max_length=250) class Skill(models.Model) : skill = models.CharField(max_length=15) class ManagerSkills(models.Model) : manager = models.ForeignKey(Manager,on_delete=models.CASCADE) skill = models.ForeignKey(Skill,on_delete=models.CASCADE) How would I query this dataset to retrieve distinct list of managers, while also having reference to associated skills that can be output in table/grid? -
Django timeseries format and highcharts
I'm trying to implement a timeseries in highcharts using Django 2.x {% for date in timeseries.all %} {{ date }} {% if not forloop.last %}, {% endif %} {% endfor %} This gives the following as output: {'flotation_date': datetime.datetime(2002, 2, 2, 0, 0, tzinfo=<UTC>)} , {'flotation_date': datetime.datetime(2002, 2, 1, 0, 0, tzinfo=<UTC>)} , {'flotation_date': datetime.datetime(2002, 2, 3, 0, 0, tzinfo=<UTC>)} , {'flotation_date': datetime.datetime(2002, 2, 4, 0, 0, tzinfo=<UTC>)} Highcharts is expecting: 1167609600000, 0.7537 ], [ 1167696000000, 0.7537 ], [ 1167782400000, 0.7559 ], [ 1167868800000, 0.7631 ], So the obvious question, how to transform the dictionary into the expected array? n.b. at this point the time has been omitted, it will be added later. -
django rest framework + mariaDB: custom JSONField handling problem
Django: v2.1.5 DRF: v3.9.1 mariaDB: v10.3 Hi, I am a DRF newbie and I have been struggling with json field. DRF does not support official json field type working with mariaDB and even though there is a 3rd-party package for mysql(django-mysql) but not compatible with mariaDB. So I searched and started implementing custom jsonfield and it looks like: model.py: enter image description here serializers.py: [enter image description here][2] views.py: [enter image description here][3] please let me know what I am doing wrong here or a way to use 3rd party package rather than custom jsonfield Thanks a lot and have a great day guys! -
Problems testing user verification view
I'm writing tests for my user verification view and I faced some problem that I don't know how to solve yet. So, here is a view I'm testing: def verify(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_verified = True user.save() print(user.is_verified) return HttpResponse('Your account was activated!') else: return HttpResponse('Activation link is invalid!') It's working fine when I run server and user gets his is_activated set to True But, here is a test: def test_new_user_verification(self): new_user = User.objects.create_user('humapen4@gmail.com', 'Abc1234567') # visit activation link link = reverse('verify', kwargs={'uidb64': urlsafe_base64_encode(force_bytes(new_user.pk)).decode(), 'token': account_activation_token.make_token(new_user)}) resp = self.client.get(link) self.assertEqual(resp.status_code, 200) self.assertTrue(new_user.is_verified) First test passes fine, but the second one fails because in the test new_user.is_verified equals to False. I don't get why is that, when I add print(user.is_verified) to the view, it prints True, but in test it's False. Any ideas why?