Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL dependent Authentification backend (SSO / Token)
I could not find any satisfying hints so far how to archive this. We habe switched to SSO for our Django application which works well so far. The point is that this does not seem to work for the Django REst Framework working with token based authentification with an extra user. Is there a way to switch authentification backend depending on the URL called? Probably I have to implement this myself but maybe there is an more elegant solution. Thanks matt -
django query for select unique rows based on foreign key field value
Hi i have two models like this class Department(models.Model): name = models.CharField(max_length=100) creator = models.ForeignKey(User) class Post(models.Model): title = models.CharField(max_length=100) description = models.TextField() is_active= models.BooleanField(default=True) department = models.ForeignKey(Deparment) post_by = models.ForeignKey(User) Users can create n number of posts from same department n number of times. But I want to fetch only one post from each department .for ex: department A has 10 users, all users are posted with same title and description Department B has 10 users, all users are posted with same title and description. now i want to fetch first created post from each department, in my results i want first created post from department A and first created Post from department B. How can i do this. -
reading from csv file to loop and insert into mysql database
I am working on a system that can send personalized messages to clients. I have a file with contacts and name. I want to upload the file then read the files. Before inserting to database, I want to add a message to it from a textbox in html templates. For instance, I will say: Dear [name], Thanks you. It will loop over the excel file and insert into database the contact and the message that has been generated like Dear Ronald, Thank you. I have managed to add to upload the excel file and insert the contacts into the database tables. But I would not be able to connect with the texttbox message Views.py def upload(request): template = 'sms/upload.html' prompt = {'order':'order of the CSV should be'} context = {} list1 =[] if request.method =="GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request,'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) # row = csv.reader(io_string, delimiter=',', quotechar="|") # next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): s = ''.join(column[0].split()) p=f"{254}{s[-9:]}" _, created = Contact.objects.update_or_create( phone_numbers = p, first_name=column[1], last_name=column[2], email=column[3], author=request.user ) context = {} # context1 = {list1} # print (context1) # print(column) return … -
Django-suit Widgets SuitSplitDateTimeWidget
I have model with two fields that is Datefield Type: I am currently using django-suit My Model class Projeto(models.Model): data_entrada=models.DateField(verbose_name="Data de entrada") data_saida= models.DateField(blank=True,null=True,verbose_name="Data da saída") i was following the docs of django-suit and i trying to do just like here i have a error that is cannot import name 'SuitDateWidget' from 'suit.widgets' My model form class ProjetoForm(forms.ModelForm): model = Projeto fields = '__all__' widgets = { 'data_entrada': SuitSplitDateTimeWidget, 'data_saida': SuitSplitDateTimeWidget, } -
Using a foreign key with django
Hello I have two tables that I defined such as : class Test(models.Model): title = models.CharField(max_length=1024, null=True, default=None) content = models.TextField(max_length=4096, null=True, default=None) user = models.ForeignKey(Water, on_delete=models.CASCADE) with the following entries : title content user_id a b 1 d e 2 class Water(models.Model): name = models.CharField(max_length=1024, null=True, default=None) color = models.TextField(max_length=4096, null=True, default=None) with the following entries : id name color 1 q s 2 f g But I noticed in my database I have a field which has the name of user_id... Do you know for instance if I want to do a query how can I do ? For instance if I define this : test = Test.objects.get(user=?).title How can I do to do a filter on user like it is user_id instead of user ? Thank you very much -
Order of operations when parsing Django templates
I am trying to figure out how Django handles the order of operations when html templates are rendered. Take the following as an example of what I am trying to answer. I have a base template that "{% includes %}" a section of code that contains a "{% block %}" statement. This base template is used in an "{% extends %}" and the "{% block %}" statement is overridden in this child template. From my testing this block is not overridden as I would expect, am I doing something wrong or is this down to the order of operations in the Django template parsing. -
VueJs and Django development environment
I am trying to get a development environment working such that a Vue app (created with vue cli) is in one docker compose service, and a django app runs in another compose service. Calling a specific url (in the django container) should return the vue app. This is to mimic how it would work in production when a specific django url returns a template response containing the vue build. However in development, it's not practical to create a vue build and copy the files over after every change. I am following the approach described here. My compose file: version: '3.6' services: db: image: postgres:11.3 volumes: - postgres_data:/var/lib/postgresql/data/ backend: build: . image: site-backend command: python ./manage.py runserver 0.0.0.0:8000 volumes: - ./backend:/code ports: - 8000:8000 depends_on: - db spa: build: context: . dockerfile: ./Dockerfile-spa image: site-spa command: npm run serve ports: - 8080:8080 volumes: - ./spa:/code - /code/node_modules depends_on: - backend volumes: postgres_data: My vue.config.js file: module.exports = { devServer: { disableHostCheck: true, host: 'spa', port: 8080 } } My django view which should return the vue spa (this is as per the above linked article): def catchall(request, upstream="http://spa:8080"): upstream_url = upstream + request.path response = requests.get(upstream_url, stream=True) content_type = response.headers.get("Content-Type") if … -
Is there some equivalent to {% url 'some-name' %} for router.register(...)
I am trying to get the URL to a specific ViewSet automatically. I tried using {% url 'api-movement' %} but get the following error: Reverse for 'api-movement' not found. 'api-movement' is not a valid view function or pattern name. I searched the web but couldn't really find what I was looking for. viewset.py class MovementViewSet(viewsets.ModelViewSet): queryset = Movement.objects.all() serializer_class = MovementSerializer router.py file: from farm.api.viewsets import * from rest_framework import routers router = routers.DefaultRouter() router.register('movement', MovementViewSet, base_name='api-movement') urls.py file: from django.urls import path, include from farm.api.responder import * from farm import views from farm.router import router urlpatterns = [ path('api/', include(router.urls)), ] html excerpt: $.ajaxSetup({ headers: { "X-CSRFToken": '{{csrf_token}}' }, }); $.ajax({ method: 'POST', url: "{% url 'api-movement' %}", data: {pk: pk}, success: function (data) { location.reload(); }, error: function (error_data) { alert('An error occurred, please reload page and try again.\n\nError: ' + error_data.responseText); } }); -
Get duplicated values from query in same model
I have model contais data like: https://ibb.co/F0WfFWy How can i get final queryset with only 'Kate', because jaste record with name 'Kate' placed in both filters results? -
why is Python2.7 rather than Python3.6 being install on elasticbeanstalk
I'm following this tutorial (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb) to work out how to set up a Django application on elasticbeanstalk. I'm getting 500 Internal Server Error so I've ssh'd into the instance and it is failing to install django2.2. When I check the python version in the virtualenv it is 2.7. I do not understand why or how to correct. This is my .elasticbeanstalk/config.yml file branch-defaults: default: environment: django-env group_suffix: null global: application_name: django-tutorial branch: null default_ec2_keyname: aws-eb default_platform: python-3.6 default_region: us-east-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application -
how to set foreign key for each files while uploading multiple filels?
here i am uploading multiple files but i got some problem while adding.The foreign key is not storing for each uploaded files.how to store the foreign key for each files selected?Itried like this but i got some error. Cannot assign "": "MoreImage.image_title" must be a "Gallery" instance. models class Gallery(models.Model): image_title = models.CharField(max_length=100, blank=True, null=True) image_date = models.DateField(blank=True, null=True) image = models.ImageField(upload_to='gallery', default='default.png') class MoreImage(models.Model): image_title = models.ForeignKey(Gallery, on_delete=models.CASCADE) images = models.ImageField(upload_to='moreimage', default='default.png') date = models.DateTimeField(auto_now_add=True) views def add_more_image(request): images = Gallery.objects.all().order_by('-date') if request.method == 'POST': form = MoreImageForm(request.POST or None, request.FILES or None) if form.is_valid(): more = form.save(commit=False) for file in request.FILES.getlist('image'): MoreImage.objects.create(image_title=Gallery.pk, images=file) #for field in request.FILES.keys(): #for form_file in request.FILES.getlist(field): #img = MoreImage(image_title_id=Gallery.pk,images=form_file) #img.save() more.save() messages.success(request, ' Images added.') return redirect('admin:add_gallery') -
Return different serializer after create() in CreateAPIView in Django REST Framework
I'm using Django 2.2 and Django REST Framework. I have to serializers for the same model. class OrderListSerializer(serializers.ModelSerializer): plan = PlanBaseSerializer(read_only=True, many=False) class Meta: model = Order fields = [ 'id', 'name', 'plan', 'pricing', 'created', 'completed', ] class OrderCreateSerializer(serializers.ModelSerializer): plan_pricing = serializers.IntegerField(required=True, write_only=True) class Meta: model = Order fields = [ 'plan_pricing' ] def create(self, validated_data): plan_pricing_ = validated_data.pop('plan_pricing', None) try: plan_pricing = PlanPricing.objects.get(pk=plan_pricing_) except PlanPricing.DoesNotExists: raise ValidationError('Plan pricing not available') validated_data['plan'] = plan_pricing.plan validated_data['amount'] = plan_pricing.price return super().create(validated_data) OrderListSerializer serializer is used for listing orders or order detail view and OrderCreateSerializer is used for creating a new order instance. The view is class CreateOrderView(generics.CreateAPIView): serializer_class = OrderCreateSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) This is working fine as the order object is creating as expected. But the returned value contains no data. I want to use OrderListSerializer to render saved order details after creating the order. How to change the serializer class after creating the object? -
How to get gmail social avatar using social-auth-app-django
I googled and got some helpful link for getting gmail avatar. I used social-auth-app-django library and following the link to setup functionality. Authentication works fine but stuck in getting avatar.I created pipeline.py inside project main configured root and called this inside my view like as from TestDjangoAuth.pipeline import get_avatar. Is this the right way i'm going through to retrieve the avatar? This is the redirect method in views.py which gives some error. i wanna set avatar as session: from TestDjangoAuth.pipeline import get_avatar def social_login(request): if request.method == 'GET': if request.user.is_authenticated: request.session['photo'] = get_avatar() This the pipeline.py that i modified to use in my view def get_avatar(backend, strategy, details, response, user=None, *args, **kwargs): url = None if backend.name == 'google-oauth2': url = response['image'].get('url') print(url) return url When i return url to use in my view to use profile picture this gives the following error AttributeError at /auth/complete/google-oauth2/ 'str' object has no attribute 'backend' -
Facing issue while connecting postgresql10.8 with django2.1.3
I am beginner in django and postgresql , i m trying to connect database but while running 'python manage.py makemigrations' got error : File "/home/trainee/portfolio/venvportfolio/lib/python3.6/site- packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: SSL error: unknown protocol expected authentication request from server, but received S requirement.txt : Django==2.1.3 Pillow==6.0.0 psycopg2==2.7.4 psycopg2-binary==2.7.4 pytz==2019.1 settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'portfolio', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '22' } } -
What is best to use ? Kivy or Django?
Im planning to create a new project for Traffic Management. Below are the objectives of my planned project: a. Plate no. detection using OpenCV b. Vehicle type, color and brand detection c. saving the output video for future uses my problem is, what is the best and most useful framework for this? is it kivy or Django framework ? -
Can I git ignore an entire branch to create a local branch that interfaces with live server, with debug set to True.?
I'm about to start deploying, and I've had some issues problems with my live server crashing, and I can't have debug set to True. I've got an idea of how I'd like things setup but I think I need some help. I have a local branch, Master, and a local database with Django Debug=True. I push Master to my server, where there's a live database, and a .env file with debug set to False. I've now setup a new local branch - debug - which has Debug=True, and using an SSH tunnel, I can connect to my live database. All I want this for, is to run my code against the live database, with debug set to True. So when something breaks on the server, as long as DEBUG and MASTER are meaningfully the same apart from the .env, I should be able to debug whatever is wrong without DEBUG=TRUE ever happening on the live, internet facing instance. What I'd like is for my local DEBUG branch to be an exact replica of MASTER, in every way, but instead of connecting to my local database, it connects to the live one via SSH tunnel, with and DEBUG = True. The … -
Django group by hour/day
I have a model: Model.py class DispatchPlan(models.Model): total_trucks = models.IntegerField(default=0) material_type = models.CharField(max_length=255, default=0, choices=mtypes) scheduled_date = models.DateTimeField(max_length=255, default=0) offered_price = models.IntegerField(default=0) weight = models.IntegerField(default=0) and I am trying to plot a graph between scheduled_date and weight. I want to group the timestamp by hour and weight accordingly. How can I do that? In SQl its just like .groupby('scheduled_date) but since it's a timestamp, I don't think it's the same Should it be like: data = DispatchPlan.objects.all().groupby('scheduled_date') I am using postgres as my database. -
How to use Jinja in Django framework?
I want to access the elements of a list using Jinja. Here in the below code both "id" and images are list. image_name is the field that stores the image {% for blog in id%} <h3>{{blog.news_title}}</h3><br/> <a href="/blog/article/{{blog.slug}}"><img src="images[loop.index0].image_name"/></a><br/> <time>{{blog.news_date}}</time><br/> <a href="/blog/article/{{blog.slug}}">click here</a><br/> {% endfor%}</li> -
how to MYSQL database setup in django using git bash?
I want to MYSQL database setup in django using git bash? so please help me immedately. thax. -
Dynamic creation of carousel
I need to create a carousel with 3 divisions per-slide. This is the model of one of the elements for each division. class Club_mem(models.Model): image1 = models.FileField() name1 = models.CharField(max_length=100) facebook1 = models.CharField(max_length=100) instagram1 = models.CharField(max_length=100) I understand I need to run a for-loop, for this, but, I'm unsure as to how to write the code. The main issue in hand is when the total number of objects is not a multiple of 3 for this I need the extra elements to be displayed and then the first element is displayed after them. Is this possible and if so how would I go about writing the code in the .html file. -
Like button will jump to the new page, how to change it to modal mode
I am learning django-comments-xtd, when I click on the Like button, it will jump to the new page. How do I make this new page popup on the current page in a modal way? Thank you. -
Django 2.2.1: Modifying the relationship of a OneToOneField
In Django 2.2.1, I have two models related via a OneToOneField: class Woman(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Man(models.Model): name = models.CharField(max_length=100) wife = models.OneToOneField( Woman, related_name = 'husband', null=True, blank=True, on_delete=models.SET_NULL ) def __str__(self): return self.name (Heteronormative for simplicity.) But as we all know, marriages fail. However, I am having a terrible time modifying the relationship: >>> john = Man.objects.create(name='John') >>> alice = Woman.objects.create(name='Alice') >>> susan = Woman.objects.create(name='Susan') >>> john.wife = alice >>> alice.husband <Man: John> # After the divorce... >>> john.wife = susan >>> susan.husband <Man: John> >>> alice.husband <Man: John> >>> susan.save() Traceback (most recent call last): ... django.db.utils.IntegrityError: UNIQUE constraint failed: appname_woman.husband_id Okay, this makes sense: Two Woman objects can't have the same husband (at least under current U.S. law). No problem; what if I delete the original wife from the relationship? >>> alice.husband = None >>> alice.save() >>> alice.husband # None >>> susan.husband <Man: John> # Oh good, no errors. And John is now married to Susan... right? Wrong. >>> john.save() Traceback (most recent call last): File "<console>", line 1, in <module> File "/project/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 415, in __get__ self.related.get_accessor_name() appname.models.Man.wife.RelatedObjectDoesNotExist: Man has no wife. It appears that the only way to make … -
What is the best way to create a multi-tabbed Django form?
I'm trying to create a multi-tabbed form using Django model forms. I need to have one submit button. Do I make tabs in Bootstrap like this or use crispy forms like this - see the section on tabs. Grateful for the guidance. -
Create an Desktop application
i need to take the screen spinning (screenshot) on client system while using django i try lots of way but it took screen shot on server , i make the executable file of the code but cant be able to call it on the client system, How to create a desktop application on python, in which the user can install the application on client system and run on it and take screen shot -
Loader for Dynamic forms (Django)
views.py I have function(for excel download) like: def download(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="test.xls"' '''my excel code writing here''' return response index.html I have anchor tag for download as: <div class="col-2"> <a href="javascript:void(0)" id="excel_dwnld"><i class="fa fa-file-excel-o"></i> Download</a> </div> And I am calling this function in js for file download as: $(document).on("click","#excel_dwnld",function(){ var testname=$("#id_testname").val(); var form = document.createElement("form"); var element1 = document.createElement("input"); form.method = "POST"; form.action= "{% url 'test:download' %}";//function call element1.value=testname; element1.name="testname"; element1.setAttribute("type", "hidden"); form.appendChild(element1); document.body.appendChild(form); //$("#loader-div").show(); // this is my loader form.submit(); }); As per my requirement dynamic form should create and that form should submit for Excel download. While form is submitting i want to show loader. And after submitting and file gets downloaded then this loader should hide. As it is a file response my loader is not hiding. Please help me out. Thanks in advance.