Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to enable login with my-website's account on other websites?
So I want to make an app store like Epic Games(let's name it "AB"). I want that the game developers can integrate my website with their games so they can provide a "Login With AB" option on their login page. Is it possible? Thank you for reading my question! -
How can I add two different slugs on two models in two different apps in Django?
I trying to add slugs to my service page and my project page, but whenever I try to run my project page I get the Page not found (404) No service found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/project/ Raised by: pages.views.<class 'pages.views.ServiceDetail'> Here's my class-based code models.py class Service(models.Model): title = models.CharField(max_length=50) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') alt = models.CharField(max_length=60, blank=True) icon = models.CharField(max_length=20) description = RichTextField() shortdesc = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) created_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('service_detail', kwargs={'slug': self.slug}) class Project(models.Model): title = models.CharField(max_length=50) category = models.CharField(max_length=50) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') alt = models.CharField(max_length=60, blank=True) client = models.CharField(max_length=50) launched = models.CharField(max_length=50) demands = models.CharField(max_length=50) description = RichTextField() shortdesc = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) video_link = models.URLField(max_length=100) created_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project_detail', kwargs={'slug': self.slug}) urls.py path('<slug:slug>/', views.ServiceDetail.as_view(), name='service_detail'), path('project/<slug:slug>/', views.ProjectDetail.as_view(), name='project_detail'), views.py def project(request): return render(request, 'project/project.html') class ProjectDetail (generic.DetailView): model = Project template_name = 'project/project_detail.html' def service(request): return render(request, 'pages/service.html') class ServiceDetail (generic.DetailView): model = Service template_name = 'pages/service_detail.html' how can I re-route so that my project page can work out? any help would be grateful -
Get request sometimes returns "There was an error: Unexpected token e in JSON at position 0"
Sometimes it will work, it seems to work when I open a new browser window. However, I can't recreate a consistent scenario when it works This is the request i'm trying to make login(): void { // const loginFormValues = JSON.stringify(this.loginForm.getRawValue()) this.userService.login(this.loginForm.getRawValue()).subscribe({ next: (data) => { console.log(data); this.router.navigate(['/']); }, error: (error) => { this.router.navigate(['/login']); console.log('There was an error: ' + error.message); }, }); } this.loginForm.getRawValue() gives me the following object {username: 'jocelyn', password: '123456'} This is what the backend does class LoginView(APIView): def post(self, request): username = request.data['username'] password = request.data['password'] # We find the first user since username is unique user = User.objects.filter(username=username).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') # Token expires in sixty minutes payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), # Date when token is created 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = {'jwt': token} return response -
CSV to Django Models specific fields
I am trying to upload a CSV into a Django Model. The problem I am encountering is, how can I write the data from my CSV to each of the fields without using indexes? Instead, write directly the field name from my CSV. with open(obj.file_name.path, 'r', encoding="utf-8") as f: reader = csv.reader(f) review_count = 0 for i, row in enumerate(reader): review_count += 1 print(i) if i==0: pass else: OrderProcessModel.objects.create( order_id=row[0], order_date=row[1], external_id=row[2], email=row[3], first_name=row[4], last_name=row[5], quantity=row[6], product_id=row[7], owner=request.user ) print(row) obj.activated = True obj.save() For example for order_id=row[0], how can I specifically write the data in order_id without using row[0]? Like order_id=row['order_id'] is not working. Thanks! -
Show separate number with comma in django tempalte
I have an issue that when the user is typing on text field the number is not separated by a comma user is typing 500000, it shows 500000 not 500,000 in models so_tien=models.CharField(max_length=50) in forms so_tien=forms.CharField(label="Số tiền",widget=forms.TextInput(attrs={"class":"form-control", 'onclick': 'numberWithCommas()',}),required=False) template file <div class="col-md-4" id="sotien" style="display:none">{{ form.so_tien}}</div> javascript code numberWithCommas in the template file: function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } Thanks for your reading -
possible to split the model based on field in DRF admin.py
I have model named organization. I am using this same model model for 2 api's. I have a field code. one API do code auto generation another API takes user entry code. I want to separate the tables based on code. Autogeneration code starts SUB001,SUB002,.... like wise. user entry code thats userwish. models.py class Organization(models.Model): code = models.CharField(max_length=255, null=False, unique=True) name = models.CharField(max_length=255, null=False) organization_type = models.CharField(max_length=255, choices=TYPES, null=False, default=COMPANY) internal_organization = models.BooleanField(null=False, default=True) location = models.ForeignKey(Location, on_delete=models.RESTRICT) mol_number = models.CharField(max_length=255, null=True, blank=True) corporate_id = models.CharField(max_length=255, null=True, blank=True) corporate_name = models.CharField(max_length=255, null=True, blank=True) routing_code = models.CharField(max_length=255, null=True, blank=True) iban = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) total_of_visas = models.IntegerField(null=False, default=0) base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT, null=True, blank=True, default=None) logo_filename = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) def __str__(self): return self.name admin.py @admin.register(Organization) class OrganizationAdmin(admin.ModelAdmin): list_display = ( 'id', 'code', 'name', 'location', 'organization_type', 'internal_organization', 'mol_number', 'corporate_id', 'corporate_name', 'routing_code', 'iban', 'description', 'total_of_visas', 'base_currency', 'logo_filename', ) Is there any possible to split models based on code,.. Really Expecting help... -
'django.db.backends.posgresql_psycopg2' isn't an available database backend
I am stuck at setting up django with postgreSQL. I have installed required packages for setup provided below. asgiref==3.5.0 Django==4.0.2 djangorestframework==3.13.1 psycopg2==2.9.3 psycopg2-binary==2.9.3 pytz==2021.3 sqlparse==0.4.2 tzdata==2021.5 and have edited DATABASES in manage.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.posgresql_psycopg2', 'NAME': 'tododb', 'USER': 'postgres', 'PASSWORD': '2993', 'HOST': 'localhost', 'PORT': '5432', } } but getting error when i runserver or make migration: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.posgresql_psycopg2' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
How To Use Reverse Relations in Django Class Based Views - 2
I'm creating a to-do list where I want the tasks to get displayed on its respective date, but I'm having a hard time doing so. I found another resource that kind of answered a similar question, but I'm still having a hard time implementing the query with reverse relations, and not quite sure how to put it on template. link Been spending 2 or 3 days stuck on this. Hope I could get some pointers here Desired Outcome Current Outcome My models: class Dailies(models.Model): date = models.DateField(auto_now_add=True) the_user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return str(self.date) class DailyTask(models.Model): task = models.CharField(max_length=255) dailies = models.ForeignKey( Dailies, on_delete=models.CASCADE ) def __str__(self): return self.task My ListView: class DailiesListView(LoginRequiredMixin, ListView): model = Dailies template_name = 'home.html' context_object_name = 'date' ordering = ['-date'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['date'] = context['date'].filter(the_user=self.request.user) context['todos'] = DailyTask.objects.filter( dailies__the_user=self.request.user) return context My template (home.html): {% if user.is_authenticated %} {% for each_date in date %} <h3> <li> {{each_date}}: {% for todo in date.dailies_set.all %} <br> {{todo}} {% endfor %} </li> </h3> {% endfor %} {% else %} ... {% endif %} -
How to create a django `models.Textchoices` programmatically?
How to create a django models.Textchoices programmatically? In the django doc, it shows you can define a model.TextChoices with: class YearInSchool(models.TextChoices): FRESHMAN = 'FR', _('Freshman') SOPHOMORE = 'SO', _('Sophomore') JUNIOR = 'JR', _('Junior') SENIOR = 'SR', _('Senior') GRADUATE = 'GR', _('Graduate') How can I create programmatically the same choices class from a list of key, values? mapping = { 'FRESHMAN': 'FR', 'SOPHOMORE': 'SO, 'JUNIOR': 'JR', 'SENIOR': 'SR', 'GRADUATE': 'GR' } # ??? YearInSchool = build_model_text_choices(mapping) -
Returning a Unix Timestamp when querying a DateTimeField
In Django, I have the following query dates = ( Event.objects.filter(cancelled=False) .exclude(id=event.id) .aggregate( first_date=Min('start'), last_date=Max('start'), next_date=Min('start', filter=Q(date__gt=timezone.now().date())), recent_date=Max('start', filter=Q(end__lt=timezone.now())) ) ) and I would like to annotate the query so that my lesson dates are returned as unix timestamps rather than datetime objects. I recognize I can simply do something like dates.next_date.timestamp(), but this causes an error when dates.next_date is None, and I'd rather not have to repeatedly check that my object is not None before getting its timestamp. How could I go about this? I have searched through many other answers and the Django docs but haven't been able to find anything I could specifically apply here. Thanks in advance! -
Email for form wont return users email inputed and just returns mine Django
hi any help please! When the user inputs a random email on the website this case "test@gmail.com" it returns my own email some reason. The message and name part of the form works tho just wondering how i can fix so that it return there email in the form. -
Having a page not found error after submitting a custom form
I have a custom html/css form that I have been working with for a bit and I have been able to get the form to render, but when I click the submit button for my form I am hit with an error of: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/register/register Using the URLconf defined in Sub.urls, Django tried these URL patterns, in this order: admin/ home/ about/ addinfo/ register/ [name='register'] The current path, register/register, didn’t match any of these. In my views.py file I have it set up to where it should redirect the user back to the homepage like so: return redirect('home/') I have 2 urls.py files, one for the registration app and one for the Main app that renders the home page and other tabs. Here is my register.urls file: urlpatterns = [ path('register/', views.register, name='register') ] Here is my main urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('home/', views.homepage), path('about/', views.about), path('addinfo/', views.addinfo), path('', include('register.urls')) ] -
Using Django-admin startproject --template on invalid cert
I am attempting to pull a template off of a local server with an invalid cert. I was wondering if there was a way to run django-admin startproject --template insecurely? (Equivalent to cURL's -k command) -
How to reference a variable from outside it's loop scope in Django template
I am sorry if the title is poorly phrased, but what i am trying to do is to use a variable that was in a for loop outside of it's scope ( in another part of the template ) here is my template: <div class="inventory-content"> <div class='category'> <div>Categories</div> <div class='category-checkbox'> {%for category in items%} <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}"> <label for="{{category.name}}"> {{category.name}}</label><br> {%endfor%} </div> </div> <div class='items'></div> </div> i want to be able to use that category variable so i can loop through all the items in that specific category and add them in the items <div>, if there is a better way to do this please guide me ! -
Custom Django context processor not returning any value
I have written a custom context processor to return some frequently-used variables. I have followed multiple tutorials and read the official documentation, but nothing is happening: the context processor is either not loading or not returning any value. I am not getting any errors. app name: auctions context_processors.py def test_context_processor(request): return { 'message': 'Hello, world.' } settings.py ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'auctions.context_processors.test_context_processor' ], }, }, ] ... layout.html ... <h1>{{ test_context_processor.message }}</h1> ... When I inspect the H1 element, it is empty - nothing was returned. It looks like this: <h1></h1> I have tried: loading the function in shell and trying it out (it works) Renaming the function Restarting server {{ test_context_processor['message'] }} (This generates an error) Complaining on SO All I can think of is that every tutorial example is using the context processor to return a list of objects from a database, whereas I'm just returning a plain string value. But surely that can't matter, right? Thanks! -
How to convert a django template to use bootstrap-table server-side pagination
I have a number of pages rendered by django templates to which I have applied bootstrap-table to implement column switching, client-side pagination, and multi-column sorting. This was after having created a fully functioning django template. My tables are very large and each column has multiple manipulations, such as: links to other pages on the site number formatting horizontal alignment (e.g. right-justify numbers) concatenating values from related tables, delimited by various strings (e.g. comma-delimiting) tooltips filling in empty values with "None" converting timedeltas to days or weeks ... A number of the manipulations utilize simple_tags and filters written in python. There's even one template that uses javascript to do some custom stuff with some colspans using bootstrap table events (e.g. $("#advsrchres").bootstrapTable({onAll: ...). And every example I look at that uses bootstrap-table's server-side pagination, there is no template and all the data is obtained using a "data-url" that returns JSON. I'm hoping I'm wrong about this, but my assessment is that I would have to rewrite all those cell decorations in the template in javascript or something. I haven't started looking into how to do it yet, so after much fruitless googling, I'm here to see if anyone knows a way to … -
Error: Invalid data. Expected a dictionary, but got InMemoryUploadedFile
I am getting the above error when trying to upload multiple pictures from react to django rest api. This is my django view code: def post(self, request, *args, **kwargs): posts_serializer = PostSerializer(data=request.FILES.getlist('image[]'), many=True) print(posts_serializer) if posts_serializer.is_valid(): posts_serializer.save() return Response(posts_serializer.data, status=status.HTTP_201_CREATED) else: print('error', posts_serializer.errors) return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is a print from posts_serializer: PostSerializer(data=[<InMemoryUploadedFile: 1PSM Logo.png (image/png)>, <InMemoryUploadedFile: Microsoft-Azure-Fundamentals.png (image/png)>, <InMemoryUploadedFile: DP-900_ProductImage-1.png (image/png)>], many=True): id = IntegerField(label='ID', read_only=True) image = ImageField(max_length=100) Appreciate any help. -
django sitemap add dynamic queryset urls
In my django website i'm trying to create the sitemap using django's sitemap app, i found difficulties in adding some queryset filtered urls, in simple words in my home page i have the url / where you can find all the posts and i'm trying to add urls that filters those posts by category for ex like this: /?category=foo /?category=bar ,checked some questions here but none of them helped here is what i used to add the home url / class PostsSitemap(Sitemap): def items(self): return ['texts'] def location(self, item): return reverse(item) so what should i add to include the filtered posts urls -
Django Error during template rendering no such column
I'm completely new to Django and data bases. I was trying to show the list of the User's to-do lists using view.html. The error says "no such column:testapp_todolist.user_id". But I don't understand where this column is and how it is related to the red line in my view.html: {% for td in user.todolist.all %} Can you please explain in details how do I add this column? Thank you. P.s. Here's my models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", default=0) name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) text = models.CharField(max_length=200) complete = models.BooleanField() def __str__(self): return self.text -
Retrieving specific object *image* from user profile to display on frontend
I am trying to query set a specific image from the Django user. My goal is to let each image have it's own page, when you click on the image from the profile page it should send you to another page with that same photo and just the photo you clicked, the page that I have already done has all the photos in order from when you posted them, I have looked through the documentation of Django 3.0 and I cannot find a query set function that allows me to get the specific image from a specific user for the function single page in views.py. All my other functions work, just wanted to show them just in case yall needed to reference to my other views.py functions. If anyone could guide me a little that would be great. views.py def profile(request, user): img = Uploads.objects.filter(profile_id = request.user.profile) profile = Profile.objects.filter(user = request.user) context = {"profile": profile, "img": img} return render(request, "main/profile.html", context) def profile_uploads(request): profile = request.user.profile if request.method == "POST": form = Uploads_Form(data = request.POST, files = request.FILES) if form.is_valid(): form.instance.profile = request.user.profile form.save() obj = form.instance return redirect('/profile/<str:user>/') else: form = Uploads_Form() img = Uploads.objects.all() return render(request,"main/profile_uploads.html", {"img":img, … -
How to speed up processing time for postgres query that is using index scan?
I am currently having a problem with long sql processing with my application for certain queries that uses Django and postgres. Using the built in django.db.connections.queries I was able to see which queries were taking the longest. I have one more complicated query that joins together 12 different tables where the majority of the processing time is being spend Using pgAdmin I was able to use the 'Explain Analyze' tool to see where the bottleneck seems to be. Most of the time is spent with on Index Scans matching the table ids. Particularly a large chunk of time is spent in this nested loop inner join I want to optimize this query, but since it is already using indexes, I am not sure how to do so. -
Django: How to list or loop multiple classes .as_view() with very similar methods. (How to simplify mutiple classes that are very similar)
I have the following classes in views.py class Base(): def function: ***blah blah blah*** return data # a list of data [data1, data2, data3, ...] class JSONView1(Base,JSONClass) def get_data(self): json_data1 = list(Base().function()[0]) return json_data1 class JSONView2(Base,JSONBase): def get_data(self): json_data2 = list(Base().function()[1]) return json_data2 JSONView1 = JSONView1.as_view() JSONView2 = JSONView2.as_view() Mainly, in class Base I build a data list, then I create 2 classes, each one calling a specific data from class Base, e.g., JSONView1 calls data1 and JSONView2 calls data2. These JSON classes are important because they convert the data to a JSON script using JSONBase (no shown here for simplicity). Finally I use .as_view() in views.py because I will call them in urls.py. The problem is that this is ok for 2 Views, but what if I have +5. I don't want to create a class for each new data in the list because the only difference between the classes is just the index, 0,1,2,3,.... the rest is the same I would like to have something like for k in range(5): class JSONView[k](Base,JSONClass) def get_data(self): json_data[k] = list(Base().function()[k]) return json_data[k] JSONView[k] = JSONView[k].as_view() Iterate over the code itself changing the index. I'm not an expert so an example to … -
How can i turn this PHP and C# code into python i can use on my Django backend? [closed]
We're trying to integrate a payment gateway into our project. Our project uses a Django backend and the example code for the integration was given in both PHP and C#. I've been trying to translate the C# or PHP into working python so i can make a working API that calls the gateway but couldn't really do it, as there are many nuances i'm not familiar with in both PHP and C#. Here is the C# code: public string ClientId = "test_ClientId"; public string ClientSecret = "test_ClientSecret"; public string ENCRP_KEY = "test_ENCRP_KEY"; public class AuthToken { public string AccessToken { get; set; } public string Status { get; set; } } public class AuthSettings { public string Url { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public string ENCRP_KEY { get; set; } } protected void Page_Load(object sender, EventArgs e) { AuthSettings myAuthSettings = new AuthSettings { Url = "URL being used for retrieving access token", ClientId = ClientId, ClientSecret = ClientSecret, ENCRP_KEY = ENCRP_KEY }; AuthToken myAuthToken = _download_serialized_object_data(myAuthSettings); Random random = new Random(); if (myAuthToken.Status == "1") { var values = new NameValueCollection { ["tij_MerchantEncryptCode"] = myAuthSettings.ENCRP_KEY, ["tij_MerchantPaymentAmount"] … -
Django form class Variables not updating from signals
I'm having a strange issue where it looks like my form is initially built on startup. I've got a variable that changes within it called location, and I can't get it to update properly. I have confirmed that the variable is updated properly via signals, so I just need to get the form to update somehow. Here's the code of the class based form: class Post(models.Model): Priority_Upload = models.FileField(default='priority', upload_to=Profile.location, blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) The variable that I have changed is Profile.location. It is initialized in profile as an empty string, "". I change it when the user logs in and on post updates, and in other parts of the code the variable is confirmed to be different. It just looks like when I define my class Post, it does it once and I can't figure out how to update it. Any help would be greatly appreciated. Thank you for your time in advance. -
POST http://localhost:8000/api/posts/ 500 (Internal Server Error)
I can not get rid of this error: POST http://localhost:8000/api/posts/ 500 (Internal Server Error) I am using a react frontend with a django rest api backend. I am trying to upload multiple images at once from an input form. It worked before with slightly different code for one image. Any ideas maybe? Here is my code: class App extends Component { state = { images: null }; handleImageChange = (e) => { this.setState({ images: e.target.files }) }; handleSubmit = (e) => { e.preventDefault(); console.log(this.state); let form_data = new FormData(); for (var i = 0; i < this.state.images.length; i++) { form_data.append('image[]', this.state.images[i]); } let url = 'http://localhost:8000/api/posts/'; axios.post(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; render() { return ( <div className="App"> <form onSubmit={this.handleSubmit}> <p> <input type="file" id="image" accept="image/png, image/jpeg" multiple onChange={this.handleImageChange} required/> </p> <input type="submit"/> </form> </div> ); } } export default App; class PostView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): posts_serializer = PostSerializer(data=request.POST.getlist('image[]')) for onepost in posts_serializer: if onepost.is_valid(): onepost.save() return Response(onepost.data, status=status.HTTP_201_CREATED) else: print('error', onepost.errors) return Response(onepost.errors, status=status.HTTP_400_BAD_REQUEST)