Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error with read JSON file lines in Django app
I have this code but I have some lines in my JSON file with empty lines. And I get this error. This is a Custom Command and I get this error. I want to create a list of jobs in The database of my Django app, I am using a For loop. Thank a lot for your help raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2) from django.core.management.base import BaseCommand from jobs.models import Job import json class Command(BaseCommand): help = 'Set up the database' def handle(self, *args: str, **options: str): with open('static/joblist03112020.json', 'r') as handle: for line in handle.readlines(): print(line) line = json.loads(line) existing_job = Job.objects.filter( job_title = line['job_title'], company = line['company'], company_url = line['company_url'], description = line['description'], salary = line['salary'], city = line['city'], district = line['district'], url = line['url'], job_type = line['job_type'], ) if existing_job.exists() is False: Job.objects.create( job_title = line['job_title'], company = line['company'], company_url = line['company_url'], description = line['description'], salary = line['salary'], city = line['city'], district = line['district'], url = line['url'], job_type = line['job_type'], ) Job.save() self.stdout.write(self.style.SUCCES('added jobs!add')) -
Adding Migrations to Source Control and Merging Conflicting Migrations in Django
I took over a Django project and discovered that migrations for various apps were not being tracked by Git. That seemed a bit problematic since my understanding was that one should always track the migrations. Is that pretty much the consensus or are there reasons not to do it? The second part of the question has to do with the fact that I have done some work involving tweaking some migrations locally. I would now like to push the changes to production. However, I am unsure as to what the best way to combine the possible conflicts would be. For instance, in production, I have the following: Untracked files: (use "git add <file>..." to include in what will be committed) mysite/aldryn_forms/migrations/0019_auto_20200730_1455.py mysite/apps/common/migrations/0016_auto_20200624_2028.py mysite/apps/common/migrations/0016_auto_20200625_1125.py mysite/apps/common/migrations/0017_merge_20200625_1129.py mysite/apps/common/migrations/0018_auto_20200720_1743.py mysite/apps/payment/migrations/0005_auto_20200624_2028.py mysite/apps/payment/migrations/0005_auto_20200625_1125.py mysite/apps/payment/migrations/0006_merge_20200625_1129.py mysite/apps/payment/migrations/0007_auto_20200720_1743.py mysite/apps/payment/migrations/0008_paymentmodel_course.py mysite/apps/payment/migrations/0009_paymentmodel_user.py mysite/apps/plugins/migrations/0016_auto_20200624_2028.py mysite/apps/plugins/migrations/0016_auto_20200625_1125.py mysite/apps/plugins/migrations/0017_merge_20200625_1129.py mysite/apps/xyz/migrations/0005_auto_20200730_1455.py Locally, I have the following: Untracked files: (use "git add <file>..." to include in what will be committed) mysite/aldryn_forms/migrations/0019_auto_20201108_1623.py mysite/apps/common/migrations/0016_auto_20201108_1623.py mysite/apps/common/migrations/0017_auto_20201108_1806.py mysite/apps/payment/migrations/0005_auto_20201108_1623.py mysite/apps/plugins/migrations/0016_auto_20201108_1623.py mysite/apps/xyz/migrations/0005_auto_20201108_1623.py These are the files with custom work: mysite/apps/common/migrations/0016_auto_20201108_1623.py mysite/apps/common/migrations/0017_auto_20201108_1806.py It appears that all the migrations existing on the production server have been applied to the production database. Hence, I have concluded that they correctly describe the state of the production DB. … -
Not getting request.POST back to view when multiple bootstrap models on same page
I'm learning some javascript and hopefully Ajax to make my django more interactive. I was able to get a single modal to work fine, but when I tried to have two separate modals, it doesn't seem that I get a post request back to the view I was using. I'm trying to take things step by step. What I had tried before also had the issue of not hangling the CRSF_Token correctly, but I made View function CRSF exempt to get around that temporarily and was going to figure that out later. My View is: @csrf_exempt def home(request): obj=Item.objects.all() form=ItemForm(request.POST) print(request.POST) if form.is_valid(): form.save() return render(request,'mainapp/home.html',{'obj':obj,'form':form}) My html that connects to the modals is: <div class="d-inline text-center"> <small class="text-muted" data-toggle="modal" data-target="#exampleModal_comment" data-whatever="{{ my_obj.id }}">Add Comment</small> <small class="text-muted">&nbsp &nbsp </small> <small class="text-muted" data-toggle="modal" data-target="#exampleModal" data-whatever="{{ my_obj.id }}">Change Rank</small> <small class="text-muted">&nbsp &nbsp </small> <a href="javascript:{document.getElementById('delete{{ my_obj.id }}').submit()}">Delete</a> </div> My html and the javascript is: <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Enter New Rank</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="{% url 'mainapp:home' %}" method="post"> {% csrf_token %} {{ form.new_rank }} <button type="button" … -
course registration system in django
I'm trying to do course registration system for a school app with django. the idea of here a program is contain multiple courses, so student can choice one program then will have courses related to that program, and they can register course for future exam. what would be the way I can handle this with django, i really need this system so bad, really would be so much appreciate for your help/suggetions..is this i can do with django? should i create separate model and views also forms for program and course? if so how can I show the form for related program's students ? thank you so much . model.py class CurrentStatus(models.Model): student = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True) current_status = models.CharField(max_length=10, choices=Current_STATUS) faculty = models.ForeignKey('Faculty', related_name='student_curent_faculty', on_delete=models.SET_NULL, blank=True, null=True) dept = models.ForeignKey('Department', related_name='student_curent_department', on_delete=models.SET_NULL, blank=True, null=True) program = models.ForeignKey('Program', related_name='student_curent_program', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.current_status class Program1_course_name(models.Model): # Program1 courses... faculty = models.ForeignKey(Faculty, on_delete=models.CASCADE, blank=True, null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True, null=True) program = models.ForeignKey(Program, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100) code = models.CharField(max_length=10) credit = models.IntegerField() def __str__(self): return (f'{self.faculty},{self.dept},{self.program},{self.name}') class Course1(models.Model): # Course1 Registration..... student = models.ForeignKey(Student, on_delete=models.CASCADE, blank=True, null=True) course = models.ManyToManyField(Program1_course_name, blank=True) def __str__(self): … -
How to filter objects with LineString field by distance to a Point?
I have a model with a LineStringField, which represents a path, as such: class Link(models.Model): # Non-relevant fields omitted geometry = models.LineStringField(srid=3067) Now, I'd like to query for objects where the distance of any point in the line string is less than a given distance (say, 100 meters). I've tried this query: lat = float(self.request.query_params['lat']) lon = float(self.request.query_params['lon']) point = Point(lat, lon, srid=4326) return Link.objects.filter(geometry__distance_lt=point, 100) However, this yields zero results, even if I increase the distance limit to hundreds of kilometers (all the test data is within about 50 km from the given lat/lon point). Is there something wrong in my query? -
How can I implement search bar in a form in Django-rest framework?
I'm new to Django-rest. I want to implement a search bar in a form to search username and location, with history and suggestions when the user starts to write. for example when the user writes "@jam" the search bar suggests "@jamesbond or @jame or ... ". can anyone tell me what should I do step by step? ps:my db is sqlit3. thank you in advance. -
populating drop down using database Django
I followed the instruction from another stackoverflow, but somehow it end up the same, the list didn't drop. so what did I do wrong to be exact? Here's my model : class Fakultas(models.Model): fakul = models.CharField(max_length=50,unique=True) def __str__(self): return self.fakul class Userdata(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) faculty = models.ForeignKey(Fakultas,on_delete=models.CASCADE,default= 1) is_voted = models.BooleanField(default=False) def __str__(self):return self.user.username Here is my Form : class UserFakultas(forms.ModelForm): faculty = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'})) class Meta: model = Userdata fields =['faculty'] def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) self.fields['faculty'].choices = [(faculty) for faculty in Fakultas.objects.all()] -
Imagefield in Django HTML Variable
I'm new to Django and trying to create a website with uploading image via Django Admin. I'm trying to view image uploaded in Imagefield in my HTML. But i just can't get the image working right. Banner.objects.all() doesn't seems able to get all the image file located in media folder. urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver from django.utils import timezone from django.contrib.auth.models import User from PIL import Image class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) #auto_now=True //auto date author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Banner(models.Model): title = models.CharField(max_length=100) images = models.ImageField(upload_to='images',null=True,blank=True) def __str__(self): return self.title views.py from django.shortcuts import render from django.views.generic import( ListView, DetailView ) from .models import * # Create your views here. class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] #arrange date posted with latest on top paginate_by = 6 def Banner_view(request): banner = Banner.objects.all() return render(request, 'blog/home.html',{'banner':banner}) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] … -
Django animated fade in of content
I have a blog website built with django and I want the user to see the posts fade in and then out as he scrolls on top of them. My code in the HTML template where the posts are looks like this: {% for post in posts %} <div> { post content ... } </div> {% endfor %} -
django-crispy-forms ImageField Design
django-crispy-forms nice tools for rendering beautiful forms faster. Problem is in imagefield. Its looks like below. Is there any prettier layout? Please help me to customize -
how to give auto sizing to images in django?
i want to build E-Commerce website And Generly it takes so many images and as you know that it's not good way to give width and height to every image so for this problem i need some one to help me to solve it in django .. -
How to implement Google, Facebook and Email login functionality in Django using firebase?
I am developing a mobile app that allows the user to login via Google, Facebook, and email. I am trying to implement it using firebase and firebase admin SDK. What is the proper way to implement this? I need to know more about the implementation login and need clarity about the following questions. How to create the user. Create the user directly from the app by using functions like signInWithCredential() and createUserWithEmailAndPassword() or user create the user with create_user() in the server using Django and firebase-admin SDK. Do we need to keep the uid in any tables in the Django database? Do we need to create the default User model provided by Django for authentication. -
How to save the social token with Django allauth?
I managed to login with Discord, everything works fine, but to do api calls for retrieving more informations (in my case the connections, also edited the scopes for it), I need the oauth2 social token. In the database there is a table called socialaccount_socialtoken, so i think allauth is able to ask for it automatically. The documentation doesn't write anything about it. Do I have to make a custom callback view which retrieves the social token and saves it to the database? -
Ecommerce books for Django junior developer
I like to follow written tutorials and learning by doing alongside with reading online documentation to get the context. I am now passionate "junior Django web developer" and i would like to build some dropshipping eshop in Django bcs it is platform that i trust and like to learn. Nevertheles i would like to know your recommendation for the books in terms of SEO, eshop UI and maybe even Django itself eventhough after bunch of online videos and books i fell in love of series of William Vincets books: "Django for Beginners" and "Django for Professionals". For SEO i heard good review for "The Art of SEO" so maybe that could be good pick. Also thinking about the dropshiping. Since i dont own any product and i want to learn how to build eshop and test it by market, i dont even know what dropshiping products could be good or not. Or what commision in % should be for me. Is there any good practical book about dropshipping too? In short i need books for like: Comprehensive guide for eshop SEO Modern UI designbook for variety of eshops Comprehensive guide for dropshipping Any recommendation please? Thank you -
django admin overriding delete_model not working with bulk delete
I want to disable deleting for a specific model instance I overrided delete_model in the ModelAdmin as follows : def delete_model(self, request, client): if client.schema_name == 'public': messages.set_level(request, messages.ERROR) messages.error(request, 'Suppression interdite pour la racine') else: super().delete_model(request, client) It works when I click the delete button on change view But not with bulk delete as the instance is deleted without preventing How can I fix this ? I also realized that delete_model is not called with bulk delete which makes a bit weird. -
Get foreign serialized ReadOnlyField on Django Rest Framework
Currently I have a model like so: class BotSerializer(serializers.ModelSerializer): class Meta: model = Bot fields = ['id', 'bot_name', 'comment', 'bot_activities'] depth = 1 class BotActivitySerializer(serializers.ModelSerializer): bot_name = serializers.ReadOnlyField(source='bot.bot_name', read_only=True) started_date_activity = serializers.DateTimeField(source='started_at', format="%m/%d/%Y %H:%M:%S", required=False, read_only=True) finished_date_activity = serializers.DateTimeField(source='finished_at', format="%m/%d/%Y %H:%M:%S", required=False, read_only=True) class Meta: model = BotActivity fields = ['started_at', 'started_date_activity', 'finished_at', 'finished_date_activity', 'bot', 'bot_name', 'bot_activity_status'] When I call the Bot seriliazer I get: { "id": 1, "bot_name": "HTTP header checker", "comment": "testtest", "bot_activities": [ { "id": 1, "started_at": "2020-11-04T15:47:26.168212Z", "finished_at": null, "bot_activity_status": "In Progress", "bot": 1 } ] } But I need to also get the started_date_activity and finished_date_activity fields. What to do to get their value too? -
DocuSign Integration. Is it possible to get auth token without users consent. I want to send docusign envolope email internally using my credentials
I have an application that sends DocuSign emails to users when clicking on a button from the frontend. So If I go by Auth code grand or implicit grant, my user has to sign in to their account. For JWT they will be redirected to consent.That means all my users need to have docusign account for sending. Is there any way to send mail from the system? -
Django constance and dajngo modeltranslations
I used Django Constance on my Django site how can I translate these things with Django model translation -
Migrations failed : error no changes detected migration django
when i run 'py manage.py makemigrations' it shows no changes detected even if i have added main as an app in settings.py And when i run 'py manage.py makemigration main' it shows no installed app with label 'main' Can someone please help ? -
Docker Compose up, Does Not Mount Named Volume When Images Are Updated
I have a docker-compose containing a Django and postgres service. I define a volume inside the docker-compose. But, when I issue docker-compose down and docker-compose up, all my data are lost. According to the docker docs: regarding docker-compose down By default, the only things removed are: Containers for services defined in the Compose file Networks defined in the networks section of the Compose file The default network, if one is used Networks and volumes defined as external are never removed. Anonymous volumes are not removed by default. However, as they don’t have a stable name, they will not be automatically mounted by a subsequent up. For data that needs to persist between updates, use host or named volumes. So, I tried using named volumes by creating a volume: docker volume create --name=postgres_db Then, in my docker-compose, I referenced this volume and emphasized external=true. Here's my docker-compose: version: '3' services: db_host: image: postgres networks: - backend-tier environment: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} volumes: - postgres_db:/var/lib/postgres/data web: image: web_image:latest command: bash -c "python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8585" # executes after running container container_name: prack_dock # name for the container volumes: - .:/src/django-docker ports: - "8888:8585" networks: - backend-tier … -
Model Formset and regular ModelForm in same template?
I got two models: Project: class Project(Model): name = CharField(max_length=50) members = ManyToManyField("accounts.User", through='ProjectUser') organization = ForeignKey(Organization, related_name="projects", on_delete=CASCADE) def __str__(self): return self.name and Task: class Task(Model): task = CharField(max_length=100) project = ForeignKey(Project, on_delete=CASCADE) class Meta: db_table = 'task' I got a UpdateView class: class ProjectUpdateView(UpdateView): form_class = ProjectUpdateForm template_name = 'projects/project_edit.html' success_url = reverse_lazy('projects:list') How can I allow a user to add tasks (through an inline formset) on the same page as where they'd edit a Project instance? E.g one consolidated form where the user can edit the Project name, and add / remove Task instances, all in one place -
Is there a way to automated a function on Django?
I have this function on my views.py, I want to automatically run it when I started python manage.py runserver. is it possible? Thanks! def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=1), ) if responses.count() >= 5: send_sms(request) return HttpResponse(200) -
how to reflect changes in postgres database to django model?
I created a new field in the database using pgadmin, I did not use django to create the field, how can I reflect the new field I created in pgadmin to django? I tried already to run python manage.py makemigration and migrate. and i receive this error. django.db.utils.ProgrammingError: column "discount_price_formula" of relation "customAdmin_product" already exists -
Displaying models in the Django admin
please help me figure out the following: firstly, we are talking about the task on the side of the standard django admin panel. let's say there are three models: class M1(models.Model): title = ... class M2(models.Model): m1 = ForeignKey(m1) name = ... class M3(models.Model): f1 = ForeignKey(m1) f2 = ManyToManyField(M2) add all 3 models to the admin panel. go from the admin panel to the 3rd model in order to create a record, select f1 (ForeignKey to M1); can this interactive be done in the standard django admin panel ?? -
Query Postgres via GraphQL in Django without models?
Is there a python library to run graphql query on Postgres database and return results. I want to be able to do the following: Client sends a graphql query Authenticate the request using django Pass the graphql query to some library or tool "which fetches required data from postgres and returns it" Return the query results to client Now how to do step 3,4? //After authenticating the user def graphql_handle(graphql_query): //run graphql_query on postgresql tables using some library or something else WITHOUT USING DJANGO MODELS. //return the details fetched in above step Is there any such tool available? After authenticating the user,I should be able to " pass the query to some graphql tool which gets required data from postgres and returns it ". Is there such a tool?