Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image field in edit mode still asking for image as a 'required' field in django form
I have a simple form with few fields. when I am trying to edit the form details its rendering perfectly but pan and aadhar fields are mandatory and asking again to upload the image in edit mode as well. If I do not want to update the documents, it should post the data with prevoius reference. But unluckly its asking me to upload image again. Could you guys please suggest me what is the problem here? Model.py class Student(BaseModel): mobile = PhoneNumberField() aadhar = models.ImageField(upload_to='img/%Y/%m/%d',blank=True, null=True) license = models.ImageField(upload_to='img/%Y/%m/%d',blank=True, null=True) pan = models.ImageField(upload_to='img/%Y/%m/%d',blank=True, null=True) form.py class AddDetails(forms.Form): mobile = PhoneNumberField() aadhar = forms.ImageField(label='Upload Aadhar',required=True) license = forms.ImageField(label='Upload License',required=True) pan = forms.ImageField(label='Opload Pan Card',required=False) views.py @login_required def add_edit(request, city_id=None, id=None): driver = None city=City.objects.get(pk=city_id) if request.method == "POST": form = AddDetails(request.POST,request.FILES, request=request) if form.is_valid(): mobile = form.cleaned_data['mobile'] aadhar = request.file['aadhar'] license = request.file['license'] pan = request.file['pan'] if Strudent.objects.filter(id=id).exists(): #updates to db stu = Student.objects.get(pk=id) stu.mobile = mobile stu.aadhar = aadhar stu.license = license stu.pan = pan stu.save() messages.success(request, 'Edits Successful...') return redirect("/student/1") else: s = Student( aadhar = aadhar,license=license, pan = pan) s.save() messages.success(request, 'Details added Successfully...') return redirect('/student/1') else: if Student.objects.filter(id=id).exists(): stu = Driver.objects.get(pk=id) form = AddDetails(initial={ 'aadhar': stu.aadhar,'pan': stu.pan, … -
Is there a django function to pass a object in database to the next redirected page in views in django
I'm developing a project in Django in which I'm using a view(verify) to verify the student's login details. If the student is valid user then it'll redirect to a page(display.html) where all the details of that particular student is displayed. How can i pass the object containing the student details from verify view to the display.html?? -
Is there a penalty for including extra template_tags in Django templates
I am reviewing a big Django project where extra template_tags are loaded on top of the template files. Are the template tags file loaded even if they are not used within the template file? Any other best practices around this? -
Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': 'NQ', 'token': '5d8-04d96d5346ae79055cf4'}' not found
I am getting this following error while I try to Reset My Password. Can anyone please solve this issue? Error: NoReverseMatch at /password-reset/ Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': 'NQ', 'token': '5d8-04d96d5346ae79055cf4'}' not found. 1 pattern(s) tried: ['password\\-reset\\-confirm/(?P<uid64>[^/]+)/(?P<token>[^/]+)/$'] Error during template rendering In template C:\Users\KIBRIA\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\registration\password_reset_email.html, error at line 6 Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': 'NQ', 'token': '5d8-04d96d5346ae79055cf4'}' not found. 1 pattern(s) tried: ['password\\-reset\\-confirm/(?P<uid64>[^/]+)/(?P<token>[^/]+)/$'] My Urlpatterns: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uid64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/',auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('', include('blog.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Daphne on Google App Engine Flexible for Django Channels app: 502 Bad Gateway Error nginx
I'm new to web development so I appreciate some hand-holding by the smart folks here. I'm trying to switch from gunicorn to Daphne for my Django app on GAE Flex, since I need to use Django Channels. I see many questions on SO (and other tutorials online) on how to use daphne on standalone linux machines but not on app engines like GAE Flex. Previously the site worked fine with gunicorn as entrypoint (in the app.yaml file). I just replaced it with daphne (I'd like to avoid changing nginx configurations, Unix sockets etc so I guess I'm ok with Daphne serving both HTTP and ws requests). So now my app.yaml looks like: runtime: python env: flex runtime_config: python_version: 3 entrypoint: daphne -b 0.0.0.0 -p 8001 my_project_name.asgi:application I've already made a .asgi file next to my .wsgi file and declared an application there. In requirements.txt I've ensured the daphne(2.4.1) and asgiref(3.2.3) packages are the latest versions. Finally when I do 'gcloud app deploy', deployment appears to happen smoothly and in the build logs I can see: Step #1: Step 9/9 : CMD exec daphne -b 0.0.0.0 -p 8001 my_project_name.asgi:application Step #1: ---> Running in c6f3762a5ce2 But I'm getting a 502 Bad … -
When I execute the django python project it shows error like ,% (desc, ENVIRONMENT_VARIABLE))
When I execute the django python project it shows error like this.Here I use the text summarization method.% (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting EXTENSIONS_MAX_UNIQUE_QUERY_ATTEMPTS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting EXTENSIONS_MAX_UNIQUE_QUERY_ATTEMPTS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. summary.py from __future__ import absolute_import from __future__ import division, print_function, unicode_literals import os from sumy.parsers.html import HtmlParser from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokenizers import Tokenizer from sumy.summarizers.lsa import LsaSummarizer as Summarizer from sumy.nlp.stemmers import Stemmer from sumy.utils import get_stop_words from applications.news_crawl.models import Details LANGUAGE = "english" SENTENCES_COUNT = 10 if __name__ == "__main__": dd = Details.objects.all() url = dd.page_url parser = HtmlParser.from_url(url, Tokenizer(LANGUAGE)) stemmer = Stemmer(LANGUAGE) summarizer = Summarizer(stemmer) summarizer.stop_words = get_stop_words(LANGUAGE) for sentence in summarizer(parser.document, SENTENCES_COUNT): print(sentence) -
How to filtering and print day by day in Django
i'd like to pritn all the moneylog in moneybook grouping by pay_day like below image. i searched and tried many method but it doesn't work. how can I use queryset manytomany model moneylog to sorting by pay_day?? moneybooks>models.py from django.utils.timezone import now from django.utils import timezone from django.db import models from django_countries.fields import CountryField from users import models as user_models from cores import models as core_models class Moneybook(core_models.TimeStampedModel): NOW = timezone.now() name = models.CharField(max_length=30, default="행복한 여행!") owner = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="owner") companion = models.ManyToManyField( user_models.User, related_name="companion", blank=True) country = CountryField() location = models.CharField(max_length=50, blank=True) start_date = models.DateTimeField(default=NOW) end_date = models.DateTimeField(default=NOW) objects = models.Manager() def get_total_price(self): total_price=self. moneylogs>models.py from django.utils.timezone import now from django.utils import timezone from django.db import models from users import models as user_models from cores import models as core_models from moneybooks import models as moneybook_models class Moneylog(core_models.TimeStampedModel): NOW = timezone.now() CATEGORY_EAT = "eat" CATEGORY_TRANSPORT = "trans" CATEGORY_SHOPPING = "shop" CATEGORY_ETC = "etc" CATEGORY_CHOICES = ((CATEGORY_EAT, "식비"), (CATEGORY_TRANSPORT, "교통비"), (CATEGORY_SHOPPING, "쇼핑비"), (CATEGORY_ETC, "기타")) moneybook = models.ForeignKey( moneybook_models.Moneybook, on_delete=models.CASCADE) pay_day = models.DateTimeField(default=NOW) payer = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="payer") dutch_payer = models.ManyToManyField( user_models.User, related_name="dutch_payer") price = models.IntegerField() category = models.CharField(max_length=10) memo = models.TextField() objects = models.Manager() def get_dutch_payer(self): return " … -
"Internal Server Error" for my Django application using Apache & Linode
I am trying to deploy my application using an Ubuntu server with Linode and I am getting an "Internal Server Error." I'll include the relevant code so if anyone can help, PLEASE! ERROR: [remote 73.XXX.162.165:57509] File "/home/admin/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup [remote 73.XXX.162.165:57509] self._wrapped = Settings(settings_module) [remote 73.XXX.162.165:57509] File "/home/admin/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ [remote 73.XXX.162.165:57509] mod = importlib.import_module(self.SETTINGS_MODULE) [remote 73.XXX.162.165:57509] File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module [remote 73.XXX.162.165:57509] return _bootstrap._gcd_import(name[level:], package, level) [remote 73.XXX.162.165:57509] File "<frozen importlib._bootstrap>", line 994, in _gcd_import [remote 73.XXX.162.165:57509] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [remote 73.XXX.162.165:57509] File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked [remote 73.XXX.162.165:57509] ModuleNotFoundError: No module named 'myapp.settings' FILE: /etc/apache2/sites-available/KLC.conf <VirtualHost *:80> ... Alias /static /home/admin/KLC/myapp/static <Directory /home/admin/KLC/myapp/static> Require all granted </Directory> <Directory /home/admin/KLC/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/admin/KLC/myapp/myapp/wsgi.py WSGIDaemonProcess django_app python-path=/home/admin/KLC python-home=/home/admin/venv WSGIProcessGroup django_app </VirtualHost> FILE: wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() -
How do I use Node.js to read server file within a Django application?
I have a django application that I use to visualize data. The data itself is in an Amazon S3 bucket, and the plotting of the data is done using bokeh. One of the applications however, uses d3 instead. And while I managed to configure the bokeh apps to work properly, I don't know how to do that with the d3 app. It has to read data either directly from S3 or locally (If I download it within django views before rendering the web page) and plot it. But whatever I try I get a 404 Not Found error. I'm learning as I go, so I don't know what I'm doing wrong. Going through SO, I found this question which gives an example of downloading a file from S3 using Node.js, but I am already running a django server so I don't know if that works. I should also mention that the files to be read are quite large (several megabytes). So, to summarize, my question is: Is using Node.js my only solution here and can it be done without having both Nodejs and django running at the same time? I'm worried that this might be too complex for me to … -
Trying to convert a string in urls.py in django to all lowercase?
Essentially, I am trying to convert a dynamic url in the form of example.com/products/productName/ into a url where the productName is all lowercase. In urls.py, I have path('products//', product_detail_view)...this should redirect to a product detail page with the productName (whatever that might be) in all lowercase. I tried appending .lower() to the 'products//' and that turned the field productName into productname which is not a recognized field in models.py. I then tried 'products//' which also didn't work at all? Anyone have any suggestions? -
Redirect to user change form in Django Admin
I have almost completed adding a PIN number field for users in the Django admin. previous question I have a separate form to change the PIN number, very similar to that seen when changing a password. I have an issue with the successful redirect after a form submit. I would like to redirect back to the user change form, but have been able to do so. What is the url pattern required to redirect to that page on a successful redirect? When submitting a new password successfully you can redirect back to the user change page therefore it is possible. -
Perfect way of using Django services in one container?
I have a Django project with a few microservices which heavily rely on django infruscucture itself. It is not possible to cut them out in sepate comtainers, unless I agree to bascially multiple the same project in different containers and use separate CMD or ENTRYPOINT at the end of each DOCKERFILE. I fount no better solution and did it that way. So now my docker-compose.yml consists out of this: dg: &dg image: python:3.7.6-alpine command: .... --> ( gunicorn --config ./gunicorn.conf.py core.wsgi:application) dg_socketshark: <<: *dg restart: on-failure ports: - 9011:9011 command: /start-dg_socketshark.sh --> (python -u manage.py run_binance) dg_run_telegram: <<: *dg restart: on-failure command: /start-dg_run_telegram.sh --> (python -u manage.py run_binance) .... other services ..... Now I got the same source folders copied in different images. It works. But the total images size is 3 times bigger than th origin folder itself. ❯ docker images REPOSITORY TAG IMAGE ID CREATED SIZE python 3.7.6-alpine a139f223ffae 9 hours ago 696MB ..... But is there a better way to use one image with microservices in it, rather than copying the same source over and over? -
Django - django-privacy-mgmt package not displaying html
I need help implementing this package this package into this django project: When viewing the page source, I see the app's HTML loaded from the render tags. But on the actual page, I am not seeing any of the outputted HTML from those render tags. Can someone please summarize a step by step set of instructions to get this package to work? The instructions provided can be confusing sometimes. I did not do the following and am not sure how to do these parts: 1) install the add-on on divio.com or via pypi (would rather not install this since it seems to costs money - unless there is a way to use it for free) 2) update your templates/django_privacy_mgmt to reflect your frontend toolchain situation (not sure where in my project to put these files. 3) Then check what kind of tracking items your website is using (either in the templates or via Google Tag Manager or in any imaginable other way) and add them in the "Django Privacy Mgmt" section of the Django Admin interface to the list of 'Tracking Items'. This is necessary so that we can show a list of tracking items to the user in the … -
Default image for imagefield doesn't store the default image
In my register form there is an ImageField where it will ask for a profile picture where I specified that it isn't required. In the imagefield from the model I assigned a default path of an image profile when the user doesn't select a profile image, but when the account is store in the database it doesn't store the default image in the situation that I said. forms.py class RegisterForm(forms.Form): GENDER = ( ("M","Hombre"), ("F","Mujer"), ) ad_profile=forms.ImageField(label="profile image",widget=forms.FileInput(attrs={'class':'form-control-file',}),validators=[validators.validate_image_file_extension,],required=False) ad_name=forms.CharField(label="name",max_length=60,min_length=15,widget=forms.TextInput(attrs={'class':'form-control',}),required=True) ad_email=forms.EmailField(label="email",widget=forms.EmailInput(attrs={'class':'form-control','placeholder': 'ejemplo@correo.com'}),required=True,validators=[validators.validate_email,]) ad_password=forms.CharField(label="password",widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Contraseña'}),required=True,min_length=6) ad_password_s=forms.CharField(label="password",widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Confirmar Contraseña'}),required=True,min_length=6) ad_username=forms.CharField(min_length=6,max_length=30,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'user1234'}),required=True) ad_genre=forms.ChoiceField(choices=GENDER,widget=forms.Select(attrs={'class':'form-control w-auto'}),required=True) models.py class QL_FREE_DT(models.Model): GENDER = ( ("M","Hombre"), ("F","Mujer"), ) ql_free_img_link=models.ImageField(upload_to="freelance-profile-picture",default='qtz_default/img/img_avatar.png') ql_free_name=models.CharField(max_length=60) ql_free_email=models.EmailField(max_length=254,unique=True) ql_free_pass=models.CharField(max_length=254)#hash256 max_length=64 bcrypt hash256 lenght=50 ql_free_username=models.CharField(max_length=30,unique=True) ql_free_gender = models.CharField(max_length=1, choices=GENDER, default="M") ql_free_desc=models.TextField(max_length=500,blank=True) ql_free_created=models.DateTimeField(auto_now_add=True) views.py def register(request): custom_errors={} if(request.method=="POST"): form=RegisterForm(request.POST,request.FILES) if(form.is_valid()): if(form.cleaned_data['ad_password'] == form.cleaned_data['ad_password_s']): request.session['qtz-email-storage']=form.cleaned_data['ad_email'] request.session['qtz-remember-storage']=True db_model=QL_FREE_DT(ql_free_img_link=form.cleaned_data['ad_profile'],ql_free_name=form.cleaned_data['ad_name'], ql_free_email=form.cleaned_data['ad_email'],ql_free_pass=make_password(form.cleaned_data['ad_password']), ql_free_username=form.cleaned_data['ad_username'],ql_free_gender=form.cleaned_data['ad_genre']) db_model.save() return HttpResponseRedirect('/login') else: custom_errors['dif-passwords']="Contraseñas no coinciden" print(form.cleaned_data) else: form=RegisterForm() return render(request,'core/register.html',{'form':form,'custom_errors':custom_errors}) PD:I already setup the media directory url and root Screenshot from the directory where you can find the path of the default profile image -
Copying the django database - PostgreSQL
I use this library to copy a database. In my view I added the following code: def MyCommand(BaseCommand): def handle(self, *args, **kwargs): # All this method needs is the path to your CSV. # (If you don't provide one, the method will return the CSV as a string.) NewCar.objects.to_csv('/home/app/app/cars.csv') CarBrand.objects.to_csv('/home/app/app/brands.csv') CarModel.objects.to_csv('/home/app/app/models.csv') Province.objects.to_csv('/home/app/app/provinces.csv') Img.objects.to_csv('/home/app/app/image.csv') ImgFile.objects.to_csv('/home/app/app/image_file.csv') and tries to copy via command python manage.py mycommand but it's return Unknown command: 'mycommand'. How can I fix it? I tried to create a file called "mycommand.py" in the folder next to manage.py and in the folder next to settings.py. But I still can't copy my database correctly. I will be grateful for any help (for each how to fix a mistake or copy using a different library). -
Format numbers in Django with Intcomma
I am having issues trying to use |intcomma to format a number. Let's say I multiply the values a and b which adds up to 1000000 by using: <h2>{% widthratio item.a 1 item.b %}</h2> All examples out there use intcomma with only one value: <h2>{{ item.a|intcomma }}</h2> So my question is, how do you combine widthratio with intcomma in order to get the multiplied number formatted as 1,000,000. Example below which do not work: <h2>{% widthratio value|intcomma 1 value|intcomma %} -
Django create a model by sending an email
I have a simple CRUD app written in Django. Is there the possibility to create a model instance, passing its attributes by sending an email to the web server that host my applucation? For example let's say in my application I have a model Book with attributes title and author, is it possible to create a new book instance (and save it on the database) just by sending an email containing the value of its attributes? Is there any reference about this? Thanks -
How to setup a User model in a Postgresql db with Django?
I have connected my Django app with a Postgresql db and currently I have a single model called Activity which is defined as: models.py at mainApp class Activity(models.Model): id = models.AutoField(primary_key=True) activity = models.CharField(null=False, max_length=10) status = models.CharField(null=True, max_length=24) initial_date = models.DateField(default=timezone.now(), null=True) ending_date = models.DateField(default=timezone.now(), null=True) responsible = models.CharField(null=False, max_length=15) I want to create a model called Users which will contain all the users that will be assigned to Activity (this is a 1:M relationship because 1 user can be assigned to several activities but no activity can be shared by several users). I want to model the Users as: models.py at accounts class MyUsers(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(null=False, max_length=20) last_name = models.CharField(null=False, max_length=20) username = models.CharField(null=False, max_length=20) email = models.CharField(null=False, max_length=20) My problems come as following: The structure of the project is based on mainApp which contains the main views.py,urls.py,forms.py, models.py configurations, and accounts which is intended to handle the login/logout and signup. Should I declare the MyUsers model in the accounts application? If so, will a foreign key be enough to connect the Activity model with the MyUsers model? class Activity(models.Model): ... initial_date = models.DateField(default=timezone.now(), null=True) ending_date = models.DateField(default=timezone.now(), null=True) username = models.ForeignKey(MyUsers, default=None) class … -
Getting pk from selected object in a generic ListView html to populate a FK for a new form (CBV)
I'm trying to make a carwash app and I am having issues getting the wash form populated with the vehicle's pk. I've tried with "get_initial", "get_context_data", "form_valid", passing {% url 'appname:urlname' object.pk %} in a html button, even thought about formsets. So if you can guide this noob in polishment (me), I would greeeeaaaatly apreciate it! so this is what the code is simplified to... model: class Car(models.Model): carplates = models.CharField(max_length=50, unique=True, null=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=False) class Wash(models.Model): vehicle_to_wash = models.ForeignKey(Car, on_delete=models.CASCADE) specific_comment = models.TextField(max_length=500, blank=True, null=True form: class WashServiceForm(forms.ModelForm): class Meta: model = Wash fields = ['specific_comment', 'vehicle_to_wash'] views: class CarList(LoginRequiredMixin, ListView): model = Car def get_queryset(self): return Car.objects.filter(user=self.request.user) def get_context_data(self, **kwargs): context = super(CarList, self).get_context_data(**kwargs) context['car_list'] = context['object_list'].filter(user=self.request.user) return context class WashService(LoginRequiredMixin, CreateView): model = Wash form_class = WashServiceForm template_name = 'service_app/standard_wash_form.html' success_url = reverse_lazy('service_app:wash_review') class WashReview(LoginRequiredMixin, TemplateView): model = Wash urls: app_name = 'service_app' urlpatterns = [ path('car-list/', CarList.as_view(), name='car_list'), path('<int:id>/select_wash/', WashService.as_view(), name='wash_service'), path('<int:pk>/review', WashReview.as_view(), name='wash_review'), ] -
Django Rest - ManyToManyField with SlugRelatedField Data Is Not Being Created
I have the following structure in my database: { "name": "sum", "formula": "a+b", "date": "2020-01-17T19:02:24.143000Z", "tags": [ "sum", "test" ], "latex": "a+b" } “tags” is a field in the Table Calculator with ManyToManyField relationship. I used an intermediate model (TagLink) that specifies the foreign keys to the calculator and tag model that are involved in the ManyToMany relationship. Models: class Tag(models.Model): name = models.CharField(max_length=25, primary_key=True, db_column='sTag') class Meta: db_table = 'tTag' class Calculator(models.Model): name = models.CharField(max_length=100, primary_key=True, db_column='sName') formula = models.CharField(max_length=200, db_column='sFormula') date = models.DateTimeField(auto_now=True, db_column='dtModifiedDate') tags = models.ManyToManyField(Tag, through='TagLink', through_fields=('calculator', 'tag'), related_name='calculator', symmetrical=False) class Meta: db_table = 'tCalculator' class TagLink(models.Model): calculator = models.ForeignKey(Calculator, on_delete=models.CASCADE, db_column='sCalculator') tag = models.ForeignKey(Tag, on_delete=models.CASCADE, db_column='sTag') class Meta: db_table = 'tTagLink' auto_created = True unique_together = [['calculator', 'tag']] Here is the Serializer: class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['name'] class CalculatorSerializer(serializers.ModelSerializer): tags = serializers.SlugRelatedField( many=True, queryset=Tag.objects.all(), slug_field='name') class Meta: model = Calculator fields = ['name', 'formula', 'date', 'tags'] def create(self, validated_data): tags = validated_data.pop('tags') calculadora = self.Meta.model.objects.create(**validated_data) for tag_ in tags: if Tag.objects.filter(name=tag_).exists(): calculadora.tags.add(tag_) else: new_tag = calculadora.tags.create(name=tag_) calculadora.tags.add(new_tag) calculadora.save() return calculadora -> I'm having trouble creating a new “tag” within the create() method; (1) Condition of Success: the tag is created … -
How do I save the selected role?
I’m using django-groups-manager. I want to select the role of the member in the member addition form. I list the roles, but I do not know how to save the selected role. How can I do it? I'm waiting for your help. Screenshot forms.py class CalisanForm(UserCreationForm): username = forms.CharField(max_length=100, label='Kullanıcı Adı') email = forms.EmailField(max_length=200, help_text='Required') password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput) group = forms.ModelChoiceField(queryset=Group.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None) roles = forms.ModelChoiceField(queryset=GroupMemberRole.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None) def __init__(self, *args, **kwargs): qs = kwargs.pop("group_qs") super().__init__(*args, **kwargs) self.fields["group"].queryset = qs class Meta: model = User fields = [ 'username', 'email', 'password1', 'password2', 'group', 'roles', ] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Parolalar eşleşmiyor!") return password2 def clean_email(self): email = self.cleaned_data.get('email') lenghtw = len(User.objects.filter(email=email)) if lenghtw > 0 : raise forms.ValidationError('Bu email adresine sahip bir kullanıcı zaten var.') return email views.py def calisan(request): queryset = request.user.groups form = CalisanForm(request.POST or None, group_qs=queryset) if form.is_valid(): user = form.save() group = form.cleaned_data['group'] user.groups.add(AGroup.objects.get(name=group)) username = form.cleaned_data['username'] member = Member.objects.create(first_name=username) group = Group.objects.get(name=form.cleaned_data['group']) group.add_member(member) user.save() password = form.cleaned_data.get('password1') new_user = authenticate(username=user.username, password=password) return redirect('home') return render(request, 'accounts/calisan/calisan.html', {'form': form, 'title': 'Üye Ol'}) -
Need help to solve newsletter form issues in base template
Here is what i have in base.html (inside the footer, so this newsletter form will be in every page) <form action="" method="POST"> {% csrf_token %} <div class="form-group"> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder='Enter email address' onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'"> <div class="input-group-append"> <button class="btn" type="submit"><span class="lnr lnr-arrow-right"></span></button> </div> </div> </div> </form> Here is the model (subscribe/models.py) class Subscriber(models.Model): email = models.EmailField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email what i have in views.py def subscribe_form(request): if request.method == 'POST': email = request.POST.get('email') new_email = Subscriber() new_email.email = email new_email.save() return redirect('home-page') here is urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.PostListView.as_view(), name='home-page'), path('subscribe/', views.subscribe_form, name='subscriber'), path('archive/', views.archive, name='archive-page'), path('category/', views.category, name='category-page'), path('contact/', views.contact, name='contact-page') ] after submitting the submit button i'm getting this error in shell Method Not Allowed (POST): / Method Not Allowed: / [18/Jan/2020 04:13:11] "POST / HTTP/1.1" 405 0 so, i'm a beginner, im trying to build a blog, but i didn't find any useful solution that can solve this issue. maybe i'm going totally wrong, but anyway if someone can help me to make this working. Thank you all. -
Does Django automatically URL decode values
If I have a django app that accepts data at /XXXX/, will Django pass me (in the view) the url-decoded or url-encoded data? Mock-up Example: def view(req, s): return HttpResponse("Is this URL-decoded? : " + s) urlpatterns = [ ..., path('<str:s>/', view), ..., ] -
zipfile write dont find files in gcloud
Im trying zip a few files from Google Storage. The zipfile of Python doesnt find the files in gcloud, just in the project. How can I do for my code find the files in gcloud? zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, 'w') as zip_file: for revenue in revenues: # queryset with files a lot, so, for a each file, add in zip t = tempfile.NamedTemporaryFile() t.write(revenue.revenue.name) if revenue.revenue.name: t.seek(0) with default_storage.open(revenue.revenue.name, "r") as file_data: zip_file.write(file_data.name, compress_type=zipfile.ZIP_DEFLATED) # the code dont pass from this part t.close() response = HttpResponse(content_type='application/x-zip-compressed') response['Content-Disposition'] = 'attachment; filename=my_zip.zip' response.write(zip_buffer.getvalue()) return response In this part, I write the file that I opened from gcloud, but stop inside the function: def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" if not self.fp: raise RuntimeError( "Attempt to write to ZIP archive that was already closed") st = os.stat(filename) # when I try find the file, the command os.stat search in project, not in gcloud the "os.stat(filename)" search for a file in project, how can I do for find in the gcloud? -
Django - Postgress - atomicly create instance only if doesn't exist
I want to create an element, but only if a 'similar' object doesn't exist. For example: name_to_be_created = "John" age_to_be_created = 15 if not Person.objects.filter(name=name_to_be_created, age__gte=age_to_be_created).exists(): Person.objects.create(name=name_to_be_created, age=age_to_be_created) Note that intentionally the condition is not simple enough to allow using get_or_create As I understand it using a transaction when using select and then insert doesn't guarantee this kind of consistency I'm using Postgres