Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way i can add a class or id to a form generated with UserCreationForm in CreateView
despite of the hours of struggle i am unable to bootstrap a django form created with UserCreationForm. i want to add bootstrap classes to the tag but due to my poor knowledge of django class based views i am unable to have a workaround. views.py class SignUp(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('accounts:login') template_name = 'accounts/signup.html' forms.py class CustomUserCreationForm(UserCreationForm): class Meta: fields = ('first_name', 'last_name', 'email', 'age', 'height', 'avatar', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password2'].label = "Confirm Password" Current Output enter image description here Output I want enter image description here -
Which would be the best way to convert a csv file to excel?
In order to become more familiar with django, I decided to build a website which is gonna let a user upload a csv file, which is then gonna be converted to excel and the user will be able to download it. In order to achieve that I created a modelform with one model FileField called csv_file as shown below: #models.py class CSVUpload(models.Model): csv_file = models.FileField(upload_to="csvupload/") def __str__(self): return self.csv_file #forms.py class CsvForm(forms.ModelForm): class Meta: model = CSVUpload fields = ('csv_file', ) and the corresponding view is: from django.shortcuts import render, redirect import pandas as pd import os #converts file from csv to excel def convertcsv2excel(filename): fpath = os.path.join(settings.MEDIA_ROOT + "\csvupload", filename) df = pd.read_csv(fpath) newfilename = str(filename) +".xlsx" newpathfile = os.path.join(settings.MEDIA_ROOT, newfilename) df.to_excel(newpathfile, encoding='utf-8', index=False) return newfilename def csvtoexcel(request): if request.method == 'POST': form = CsvForm(request.POST, request.FILES) if form.is_valid(): form.save() print(form.cleaned_data['csv_file'].name) convertcsv2excel(form.cleaned_data['csv_file'].name) return redirect('exceltocsv') else: form = CsvForm() return render(request, 'xmlconverter/csvtoexcel.html',{'form': form}) right now as you can see I am using Pandas in order to convert the csv file to excel inside the views.py file. My question is, is there a better way to do it (for instance in the form or model module) in order to make the excel … -
Selected options in Django variable
How to save the selected options from a multi select drop down in a Django variable as a list ? Is there anything to be imported from the .html to .py? -
Edit urls in wagtail (social-auth-app-django problems)
I want to add social-auth-app-django to my wagtail project to let normal users comment posts on blog. To make social-auth-app-django work, I need to add this urlpattern: urlpatterns = [ url(r'^auth/', include('social_django.urls', namespace='social')), ] How to do it? I didn't find any way to edit urls.py in wagtail, and I didn't find any social-auth-app-django wagtail equivalent. -
How to use PayTM payments integrated Android app with Django backend?
I have integrated PayTM payments in my Android app which has a Django backend. Previously we used Stripe payment for payments. but now as we are switching from stripe to PayTM payments (due to regional availability), here are the few questions: Do we need to use PayTM Django library? We did use Stripe payments Django lib. previously (pip install..) With Stripe, we used to send Stripe token via POST to Django and after Django authenticating it wrt to Stripe, we would get json response as a success. This json response "success" would trigger other functionalities of android app. According to some tutorials, to integrate PayTM in Android app, I have upload CHECKSUM files to a server (this server is not the Django backend, I uploaded to hosting web service and just grabbed the URL pointing to Checksum file) Currently, I get status TXN_SUCCESS or such responses on PayTM transaction done successfully. Basically, how do I use PayTM payments in Android app only with Django as backend? buttonPaytm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ContextCompat.checkSelfPermission(PaymentActivity.this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(PaymentActivity.this, new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 101); } final String M_id = "Ulbgcl83114033677105"; final String customer_id = UUID.randomUUID().toString().substring(0, 28); final String … -
radio buttons incorrectly written to the database in django
I've a registration form, where user must chose one of 2 options. Django renders all correctly, django admin also have it ok, but db records all possible choices as value. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email','password1','password2'] class UserProfileForm(forms.ModelForm): terms_compliance = forms.BooleanField(label=mark_safe('I agree with <a href="/questions/whyname/" target="_blank">terms and conditions </a>')) class Meta: model = UserProfile widgets = {'role': forms.RadioSelect} fields = ('role','terms_compliance') def __init__(self): self.fields['terms_compliance'].initial = True models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role_choices = [('publisher','Издатель'), ('advertiser','Рекламодатель')] role = models.CharField(max_length=15, choices=role_choices, default=None) terms_compliance = models.BooleanField() def __str__(self): return self.user.username In new instance (which is user.userprofile.role_choices) I need advertiser or publisher, but all I have is: [('publisher','Publisher'), ('advertiser','Advertiser')] -
How to manage memberships of clubs/teams (groups) and handle permissions in Django?
I'm creating a Django project to help people run clubs and community groups. I'm new to Django and I can think of lots of different ways to add users to clubs and manage permissions, but it's not clear what the right way to do it is. I have a "Club" model and a "Team" model. A club can have many teams, and members of a club may or may not be members of a team, but a user must be a member of the club in order to join the team. There will also be various permissions around what a club/team member can and cannot do (and what a club/team administrator can do) My current plan for managing membership is to create "ClubMembership" and "TeamMembership" models and create the relationships using ManyToManyField.through, as demonstrated here: https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ManyToManyField.through For permissions, it looks like I should use django-guardian and set permissions when people join/leave a club/team. Would it make sense to also have a "members" foreign key to django.contrib.auth.models.Group in my club/team models to keep track of this? It feels like I'm doubling up in some areas by having membership managed by membership models and then also using groups to set permissions. Is … -
How to query data from existing sql database mac os
I am creating a new website and want to take in a form from the user and using this query a specific set of tables in an external database, then return this data. I have not found any information using this. People always seem to use models but I have roughly 5000 tables each contating thousands of rows so there is no way to do this efficiently. To summarize, what is the most simple way to query a external database. eg. I want to use this query, use databasename SELECT * FROM table_name WHERE id = user_input; -
psycopg2 can't install in virtualenv 2.7 in Mojave - macOS - 10.14.5
I am having this error: macosx-10.14-intel-2.7/psycopg/adapter_pfloat.o build/temp.macosx-10.14-intel-2.7/psycopg/adapter_qstring.o build/temp.macosx-10.14-intel-2.7/psycopg/microprotocols.o build/temp.macosx-10.14-intel-2.7/psycopg/microprotocols_proto.o build/temp.macosx-10.14-intel-2.7/psycopg/typecast.o -L/usr/local/lib -lpq -lssl -lcrypto -o build/lib.macosx-10.14-intel-2.7/psycopg2/_psycopg.so ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'cc' failed with exit status 1 When I am installing psycopg2 in macOS not in virtualenv - this helped me: psycopg2 sierra Answer by @zganger But when I am in virtualenv 2.7 (venv) - nothing works, none of the answers even in that post. I was trying to solve this for a week and no luck at all. Not sure what I else I can do. -
Django querying
I have writing a code where I need the value of the total frequency of words. I need to multiply this value to another value, but I can't do that because my code is returning a query set ({frequency_sum: 15}). All I need is the 15, so I can multiply with other variables, please how do I write the code so when I request for Dictionary. Objects.aggregate (Sum(frequency)), I could get just the 15 and nothing else -
How to asynchrony exchange a uri on img
There was a problem with Django, namely: 1. There is in template field entry and the <input class="uri-com" placeholder="URL on community" value="" onchange="addComURI(this.value)"> <img id="fg-photo-50" class="community-50" src="{% static "img/community_50.gif" %}"> When you add a link to a third-party resource in input, I want to replace the original image, the one that is located on this link. Download to itself under this its not want. I'm replacing the value of the img tag in JS document.getElementById("fg-photo-50").src = this.responseText; The link is replaced but taking into account the connected statics to a template, i.e. before the link adds the address of my host server http://127.0.0.1:8000/%22https://getcim.com/RwO3inNPejmv9mTnK24R8EESIkhA/V6NXerYvQks (The link is not working) Who will tell you how to properly replace the link to the image? -
How to fill form fields with model values
I am trying to fill my form with data from model Good. I use filter by id to get certain objects. I've needed to rewrite init function to set a working queryset, and it works. Now I need to fill values for other fields. This is my forms.py: class GoodGet(forms.ModelForm): class Meta: model = Good_Get Size = forms.ModelChoiceField(queryset = Good.objects.all()) Name = forms.CharField(widget = forms.TextInput(attrs = {'value': Good.objects.all()})) fields = '__all__' def __init__(self, *args, good_id1=None, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) if good_id1 is not None: obj = Good.objects.filter(id = good_id1) for good in obj: good_sizes = good.Size.all() self.fields['Size'].queryset = good_sizes I need to do something like this: def __init__(self, *args, good_id1=None, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) if good_id1 is not None: obj = Good.objects.filter(id = good_id1) ---> self.Name = obj.Name <--- for good in obj: good_sizes = good.Size.all() self.fields['Size'].queryset = good_sizes So, how can I fill the values of other fields with data from model Good? -
I want to make imagefield optional in my form.I tried blank = True But its not working?
I want to set imagefield as optional in my form.For that i gave blank = True null = True but it,s not working.There are some question in stack overflow related to my question i tried all their answers but didn't worked ? models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='null',upload_to='pics',blank=True) view.py def register(request): if request.method == "POST": form = Register(request.POST,request.FILES) if form.is_valid(): email = form.cleaned_data['Email'] User_name=form.cleaned_data['Username'] Password=form.cleaned_data['Password'] firstname=form.cleaned_data['Firstname'] lastname=form.cleaned_data['Lastname'] user=User.objects.create_user(username=User_name, password=Password,email=email,first_name=firstname, last_name=lastname) insert = Profile(image = request.FILES('picture', None),user=user) return redirect('/') forms.py class Register(forms.Form): picture = forms.ImageField() #i am posting only imagefield code -
Python (Windows Server) Virtualenv not recognizing Django is installed
My virtual environment refuses to recognize my install of Django (strangely) I'm on Windows Server, installed Python 3.7 to a directory (C:\Python37) which I have C:\Python37;C:\Python37\Scripts in my windows Path so when using Powershell or GitBash I can use the python command. if I run where python it shows the default install I CD into my django project directory and run: python virtualenv venv and the venv directory is created Then I run source venv/Scripts/activate and it activates appropriately. When I run where python it shows the exe inside the venv directory - which is expected and appropriate. I run pip install -r requirements.txt and all my requirements install appropriately. I confirm they are installed with pip freeze (all installed correctly) Once I do that I go to run python manage.py collectstatic (no migrations are required in this particular instance) I get an error message that Django isn't installed. To check this, with my virtualenv still activated I enter the shell (python) If I do import django it also says Django is not installed. I cannot figure out what's happening here - the python version appears to be correct, the correct virtualenv is activated - but it's still not seeing … -
Cannot assign "40": "Group.groupParent_id" must be a "Group" instance
I want to add group from my group model. this one is recursive on parent-children relation. But when I want to create a group with a children. I have the error my model: class Group(models.Model): group_id = models.AutoField(primary_key=True) groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) group_name = models.CharField(max_length=100, null=False, blank=False, unique=True) views.py: My function which provoke error on line 18 GroupParent_id : def add_group_fromcoa(request): # add type and subtype of chart of account as first serie of group and subgroup # ------ Type adding ----- types = ChartOfAccount.objects.order_by().values_list("field_type", flat=True).distinct() for type_types in types: upload_data = Group.objects.get_or_create(group_name=type_types,) types = ChartOfAccount.objects.order_by().values_list('field_subtype', flat=True).distinct() for type_types in types: looktype = ChartOfAccount.objects.filter(field_subtype=type_types).values('field_type').first() print("retour Groupe: {}".format(looktype['field_type'])) looktyp= Group.objects.filter(group_name=looktype['field_type']).values('group_id').first() print("IDGroup: {}".format(int(looktyp['group_id']))) upload_data = Group.objects.get_or_create( group_name=type_types, groupParent_id=int(looktyp['group_id'])) return redirect(home) -
Image url from an ImageField used as ForeignKey
I'm trying to see an image inside a template using this tag {{ post_details.header_image.url }}. When I do this the image doesn't appear. models.py class ImageUpload(models.Model): name = models.CharField( max_length=50, ) file = models.ImageField( upload_to='images/%Y/%m/%d', ) class BlogPost(models.Model): title = models.CharField( max_length=70, unique=True, ) slug_post = models.SlugField( 'Slug', max_length=70, unique=True, ) contents = models.TextField( 'Contenuti', blank=True, ) header_image = models.ForeignKey( ImageUpload, on_delete=models.CASCADE, related_name="blog_header_image", blank=True, ) views.py def singlePost(request, slug_post): post_details = get_object_or_404(BlogPost, slug_post=slug_post) context = { "post_details": post_details, } template = 'blog/reading/single_post.html' return render(request, template, context) single_post.html <img src="{{ post_details.header_image.url }}" class="img-fluid" alt="{{ post_details.title }}"> <h1>{{ post_details.title }}</h1> <p>{{ post_details.contents }}</p> I can see the title and the contents but the image tag appear blank. How I can solve this problem? -
I am getting only default apache test page after installing ssl on django application
after installing ssl certificate, I have changed the Apache configuration files, so now I am seeing only default Apache test page I tried to change the default configuration file and ssl configuration file with many changes. default config file <VirtualHost *:80> Redirect permanent / https://www.piping.pro/ ServerName localhost ServerAdmin admin@piping.pro ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> ssl config file <VirtualHost *:443> ServerName localhost ServerAdmin admin@piping.pro Alias /static /var/www/static-root <Directory /var/www/static-root> Require all granted </Directory> Alias /media /var/www/media-root <Directory /var/www/media-root> Require all granted </Directory> <Directory /var/www/venv/src/mysite> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine on SSLCertificateFile /etc/ssl/piping_pro.crt SSLCertificateKeyFile /etc/ssl/private/PrivateKey.key SSLCertificateChainFile /etc/ssl/piping_pro.ca-bundle </VirtualHost> Eventhough all my files are uploaded to server why I am not gettingg the desired pages -
How to use Django dumpdata for exclude users who do not have administrator privilege
Please, could anyone tell me the way to use Django dumpdata excluding users who do not have privileges? Thanks, -
Check if user already submitted form in django
In views i have a function that returns two forms, on is a survey and the other one is the survey update form. If the user submitted the survey i would like to refresh the page and shows the update form. But i dont know how to check if the user submitted the form or created the object in order to implement an if function, if form submitted show the update on else show the survey. -
Where can I put an executable in django without using a virtual environment?
Whenever I run >>python manage.py migrate , it says "Importerror no module named Django.core.management" I got the files from a Django tutorial boilerplate. I think I isolated the problem to not having a virtual environment and the executable doesn't know where to go. I currently have #!usr/local/lib/python2.7/site-packages as my shebang. I also don't know what to have as my shebang. I don't want to use a virtual env. If it helps, I am using python 2.7 and Django 1.8 Also don't know why this happens but when I run django-admin.py --version or python -m Django --version it says command not found or no module named Django respectively. But when I run Django-admin --version, it is fine. I am very new to Django and python. Thanks. -
Set cookie in GraphQL mutation
I need to update a cookie in GraphQL mutation using graphene and Django. My first idea was to add cookie to context (which is request) and then set it in middleware. I have a very simple mutation that looks like that: class SetWantedCookieMutation(graphene.Mutation): class Arguments: wanted_cookie = graphene.String(required=True) ok = graphene.Boolean(required=True) def mutate(self, info, wanted_cookie): # set cookie here info.context.wanted_cookie = wanted_cookie return SetWantedCookieMutation(ok=True) And Django Middleware is that: class CookieMiddleware(MiddlewareMixin): def process_response(self, request, response): if (hasattr(request, 'wanted_cookie')): response.set_cookie('wanted_cookie', request.wanted_cookie) return response But I cannot get currency_code in my CurrencyCookieMiddleware. Any ideas how to set cookie in mutation/moddlewere? Or what are other ways to set cookie through graphene mutation? -
Django "PostgreSQL" add non-nullable field
I'm new learner in django, i have a minor problem i added slug field in model.py file and i run python manage.py makemigrations code: . . . slug=models.SlugField(unique=True) So, command prompt said that, (sorry for my bad english) 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: My questions is; What should I do? -
Getting Django admin emails for deleted pages
I am reporting a weird behavior with Django admin emails (or at least I think it's weird as I don't really know the cause). When a server error occurs, for instance I navigate to a page that does not exist, I get the 500 error and the relative email gets sent to me and this is correct, all good. The problem I am having is that I am getting a lot of this admin emails for old pages that I have deleted (even very old, like deleted more than one year ago). I am not navigating to those pages, and I'm pretty positive there are no links on my website (or other websites) that point to those pages. Also, my google analytics is not recording visits to these specific pages, while if I navigate to a 500 error page on my browser, google analytics records the visit. I really have no clue about this, any ideas? A little more about the setup: the website is in the sports analytics field. We try to analyze all the matches that we cover and provide information about the match on a specific page. I set up the website so that each analyzed match … -
How can I capitalize first word of "lorem" template tag output in Django 2.2?
Django provides a useful "lorem" template tag that will output some "lorem ipsum" text, but the text is all lowercase. How can the first word be capitalized, to get "Lorem ipsum ... "? I know that if I had a string I could run it through a filter, but I don't know how to filter the output of a tag. -
Sending href and id of clicked link from page to django using Ajax
I have an on click JQuery event handler that I want to use to send the href and id of any clicked link to my Django server. But I am having a hard time finding a good tutorial/info about using Django with Ajax. Let's say I want to send the id and href of the link, have Django check if the link has https, and send the href along with a message back as a response. Something like: $("a").on("click", function(e){ e.preventDefault(); if(e.target.href){ let id = e.target.id; let href = e.target.href; $.ajax({ url: "/nameOfFunction/", data: {"id":id, "href":href}, type: "POST", success: function(response) { if(response.msg=="yes"){alert(response.href+" is Secure")} else{alert(response.href+" is Not Secure")} }, error:function(error) { console.log(error); } }); } }); def nameOfFunction(request): if ("https" in request.POST.get("href")): msg = "yes" else: msg = "no" return ({"msg":msg, "href":href}) Can someone help me fix this so that it works?