Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my User Registration Page Gives 'The view didn't return an HttpResponse object. It returned None instead.' Error?
I want to create a user registration form in django by following django tutorial part 15. However, here's an error that is on my way. My views.py is from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render,redirect def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('/polls') else: form = UserCreationForm() args = {'form': form} return render(request, 'polls/reg_form.html', args) And, it is giving an error. The view polls.views.register didn't return an HttpResponse object. It returned None instead. -
django update table without form
Why i can't update my table when i was wanted to insert to database? def insert3(request): inputasset3 = InputAsset3.objects.all() DT = datetime.datetime.now().date() for a in inputasset3 : if a.nama_field == "Subang Field" and a.date.date == DT: InputAsset3.objects.update(InputOil_Target=InputOil31) InputAsset3.objects.update(InputOil_Target=InputGas31) else: input1 = InputAsset3.objects.create( id_Kode_field = get_object_or_404(Asset3,pk=1), nama_field = "Subang Field", Gas_Target = Asset3.objects.values_list('Gas_Target',flat=True)[0], Oil_Target = Asset3.objects.values_list('Oil_Target',flat=True)[0], InputOil_Target=request.POST.get('InputOil31', False), InputGas_Target=request.POST.get('InputGas31', False) ) input1.save() if a.nama_field == "Jatibarang Field" and a.date.date == DT: InputAsset3.objects.update(InputOil_Target=InputOil32) InputAsset3.objects.update(InputOil_Target=InputGas32) else: input2 = InputAsset3.objects.create( id_Kode_field = get_object_or_404(Asset3,pk=2), nama_field = "Jatibarang Field", Gas_Target = Asset3.objects.values_list('Gas_Target',flat=True)[1], Oil_Target = Asset3.objects.values_list('Oil_Target',flat=True)[1], InputOil_Target=request.POST.get('InputOil32', False), InputGas_Target=request.POST.get('InputGas32', False) ) input2.save() if a.nama_field == "Tambun Field" and a.date.date == DT: InputAsset3.objects.update(InputOil_Target=InputOil33) InputAsset3.objects.update(InputOil_Target=InputGas33) else: input3 = InputAsset3.objects.create( id_Kode_field = get_object_or_404(Asset3,pk=3), nama_field = "Tambun Field", Gas_Target = Asset3.objects.values_list('Gas_Target',flat=True)[2], Oil_Target = Asset3.objects.values_list('Oil_Target',flat=True)[2], InputOil_Target=request.POST.get('InputOil33', False), InputGas_Target=request.POST.get('InputGas33', False) ) input3.save() break return render(request,"index/datasaved.html",{}) -
Django local development, Chrome Blocking requests to local server in frame
Im developing a web application using the local dev server provided by Django. My local web-app is to be emmbeded in an iframe of a remote site. But when testing Chrome loads the remote site encappsulating webpage (page which is meant to wrap my web-app in an iframe but blocks requests towards my local dev server in the iframe, which makes testing impossible. I have looked in chrome's console and get the following error: Refused to frame 'https://localhost:8000/' because it violates the following Content Security Policy directive: "child-src 'self' https://* shopify-pos://*". Note that 'frame-src' was not explicitly set, so 'child-src' is used as a fallback. My questions: 1) Why is Chrome blocking requests? 2) Is this error being caused because I am using localhost? and framing work fine on Chrome once I deploy on a production server with domain name? 3) Is there anyway that I may circumvent this error while I am on local host for testing purposes? -
How to highlight code when posting on a website dynamically?
I'm having a website made with django it is basically a tutorial website and i want to highlight code dynamically into my tutorials what should i do? -
Django environment error in pulled Pycharm project
I created a new Django project in pycharm and ran it on my system. Works fine without any issues. I pushed the project to github. But when my teammates pull the same project, they face issues with the configuration. There are questions available on SO regarding this but none of them seemed to solve my issue and pycharm throws the same Error: Django is not importable in this environment. Here are some of the troubleshooting techniques I tried but to no use: Checked the project python interpreter on my teammates system. It is correctly setup. Pushed the project first with and then without the .idea folder. I thought there might have been some issue with the config there but both didn't work. Created a new virtual environment which gets setup correctly but again does not work. Is there something obvious that I am missing? Any pointers as to which files to ignore and which files to push in Django while working in a team so that the configurations do not conflict? -
form object has no attribute 'email' in django
I have a registration form made of 2 forms, from which email field gets saved in both User and Student models. Now, I made an update account info view. Problem is, I want that email will get updated the in both models. But I get error: 'StudentEditForm' object has no attribute 'email' Here is my code: class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=False) name = forms.CharField(max_length=30) surname = forms.CharField(max_length=50) photo = forms.ImageField(required=False) phone = forms.CharField(max_length=15, required=False) class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')], null=True, blank=True, default=None) photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None) phone = models.CharField(max_length=15, null=True, blank=True, default=None) def __str__(self): return self.surname User.student = property(lambda p: Student.objects.get_or_create(user=p)[0]) def profile_edit(request): user = request.user student = request.user.student if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) user.email = form.email form.save() return render(request, 'index.html') context = { "form": form, } return render(request, "registration/profile_edit.html", context) Again, I need that I will be able to update the email … -
Django foreign key issue
I have a requirement where I am creating user and want to define foreign key relation by creating other user and link both. Mean user1 is created by user2 and user2 is stored in different model. user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) Not sure about how to implement this. Help appreciated! -
Django somehow cannot determine simple annotate function
I'm trying to create an annotation on a queryset class that simply adds a boolean that is the result of some standard queries. CustomQueryset(models.QuerySet): """ An extension of the traditional queryset to support filtering on accepting_offers """ def annotate_with_accepting_offers(self): """ Add a lovely little variable to the SELECT that says if the listing is accepting offers. A <thing> is accepting offers when its: + not cancelled + expire date is today or in the future + has spaces left """ return self.annotate(accepting_offers=Q(cancelled=False) & Q(expire_date__gte=date.today()) & Q(spaces_left__gt=0)) This unfortunately does not work, any ideas what annotation would? If this was SQL, the top line would look like: SELECT *, (cancelled=False AND expire_date >= ? AND spaces_left > 0) AS accepting_offers -
Python/Django: Offering a zip file for download from io.BytesIO buffer
I'm trying to put a zip file into an io.BytesIO buffer and then offer that for download. Below is what I've got (part of a longer views.py, I'm just posting the relevant part). But I'm getting the error message "AttributeError at / 'bytes' object has no attribute 'read'". Can anyone tell me what I'm doing wrong? from django.http import HttpResponse from wsgiref.util import FileWrapper from zipfile import * import io buffer = io.BytesIO() zipf = ZipFile(buffer, "w") zipf.write ("file.txt") zipf.close() response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=file.zip' return response -
How can i delete database table in django?
I changed my models and made migrations. Then i changed my models another one time and when try python manage.py migrate i get error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, shop Running migrations: Applying shop.0004_auto_20180128_1331...Traceback (most recent call last): File "/home/morilon/dj/intshop/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/home/morilon/dj/intshop/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 301, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: table "shop_brand" already exists So my question is - how can i delete table "shop_brand"??? I already tried flush and sqlflush but that only delete data from table but not actually table "shop_brand". I use django 2.0.1 and python 3.6 -
How A Django ManyToManyField Can Be Described Long Hand In A Template
Given the following Django Tmeplate, how do I set the selected items on a failed submission. I have figured out that {{option.value}} gives me an array of unicode values that represent the selected items but unsure how to compare them successfully with {{option.choice_value}} as this does not have the u"" declaration like set([u'26']) does for option.value! {% for option in request_session_form.availability %} <input type="checkbox" name="{{option.name}}" value="{{ option.choice_value }}" id="{{option.id_for_label}}" /> <label class="option" for="{{option.id_for_label}}">{{ option.choice_label }}</label> {% endfor %} Any help apreciated. -
In django_debug_toolbar how can I see the queries on submit
I'm doing some extra queries(using object attributes) on submit/save(to define the file upload_to) and I want to see them in the django_debug_toolbar. I'm doing the same queries for each file, and I want to do some optimization, to see how many there are, is just one call, or are called for each attribute. -
URL not working with One-Time-Token
I'm trying to build a login system where the user - after sign up - needs to click on a link an an activation email. I create the token in a method: def get_context_data( self, request, user, context=None): if context is None: context = dict() current_site = get_current_site(request) if request.is_secure(): protocol = 'https' else: protocol = 'http' token = token_generator.make_token(user) uid = urlsafe_base64_encode( force_bytes(user.pk)) context.update({ 'domain': current_site.domain, 'protocol': protocol, 'site_name': current_site.name, 'token': token, 'uid': uid, 'user': user, }) return context The problem here is that the generated token looks like this: http://127.0.0.1:8000/user/activate/b&#39;NjA&#39;/4t8-9fad2c2dc78ecf8a1228/ The URL is not working with the urlsafe_base64_encode(force_bytes(user.ok)) generates a weired token that does not work in an url. If I try to click on the link I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/user/activate/b& as you can see, the url is cutt off after the #&. How can I encode the user.pk in a way that will work in the url -
Saving Many-To-Many Field with self-reference in django-admin
I am trying to save a many-to-many field with self reference through django-admin. This is my model: class QuestionSetCategory(models.Model): parent_categories = models.ManyToManyField('self', blank=True) When I save the relation with django-admin, it outputs the following error: "<QuestionSetCategory: Test>" needs to have a value for field "id" before this many-to-many relationship can be used. I think it is because, the category itself needs to be saved, before the reference to the field can exist. I read about overriding the save-method in my ModelForm, but I dont know, how to exactly do this. I tried some solutions, but don't get the point. Thanks for help in advance. -
I want different forms according to share_type choices field without submitting the form, how can i do it in Django?
SHARE_TYPE = (('SECONDARY ', 'secondary'), ('IPO', 'IPO'), ('RIGHT', 'Right'), ('BONUS', 'Bonus'), ) class PurchasedShare(models.Model): transaction_date = models.DateField() transaction_number = models.IntegerField(unique=True) quantity = models.PositiveIntegerField() rate = models.DecimalField(max_digits=10, decimal_places=2) broker = models.ForeignKey(Broker, on_delete=models.CASCADE) share_type = models.CharField(max_length=150, choices=SHARE_TYPE) symbol = models.ForeignKey(Company, on_delete=models.CASCADE) portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE) shareholder = models.ForeignKey(ShareHolder, on_delete=models.CASCADE) def __str__(self): return str(self.symbol) For eg, if i select IPO share_type, then create forms having fields symbol,quantity,rate and portfolio only and if i select secondary share_type create forms having all fields. -
post() got an unexpected keyword argument 'uidb64' Reset password rest_auth
now i work on reset password with rest_auth what ever the email be sent and url be open like this : This is the page when i click on url sent in email and after the fill the fields and make a post request i get this : This is the error i get and here is my urls : urlpatterns = [ path('', include('rest_auth.urls')), path('login/', LoginView.as_view(), name='account_login'), path('registration/', include('rest_auth.registration.urls')), path('registration/', RegisterView.as_view(), name='account_signup'), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), re_path(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm') ] -
Django migrate sqlite3 db to postgres Query invalid input syntax for integer: "none" error
My project use Django 2.0 database from sqlite migrate to postgresql 9.6.3, Run normal in sqilet, migrate to postgresql and running error. models.py : Class WechatPay(models.Model): user = models.CharField('网点', max_length=20, default='None') user_group = models.CharField('渠道', max_length=20, default='None') total_fee = models.FloatField('订单金额', default=0, decimal_places=0, max_digits=7) card_sale = models.FloatField('售卡款', default=0, decimal_places=0, max_digits=7) card_recharge = models.FloatField('充值款', default=0, decimal_places=0, max_digits=7) trade_date = models.DateField('交易日期', auto_now_add=True) views.py : def group_list(request): start_time = request.GET.get('start_time', datetime.today().strftime("%Y-%m-%d")) end_time = request.GET.get('end_time', datetime.today().strftime("%Y-%m-%d")) object_list = WechatPay.objects.values('user', 'trade_date', 'user_group').filter( trade_date__gte=start_time).filter( trade_date__lte=end_time).filter( status='SUCCESS').annotate( card_sale=Cast(Sum('card_sale'), DecimalField(decimal_places=2)), total_fee=Cast(Sum('total_fee'), DecimalField(decimal_places=2)), card_recharge=Cast(Sum('card_recharge'), DecimalField(decimal_places=2)) ).order_by('-trade_date') summary = WechatPay.objects.filter( trade_date__gte=start_time).filter( trade_date__lte=end_time).filter( status='SUCCESS').aggregate(card_sale_sum=Cast(Sum('card_sale'), DecimalField(decimal_places=2)), total_fee_sum=Cast(Sum('total_fee'), DecimalField(decimal_places=2)), card_recharge_sum=Cast(Sum('card_recharge'), DecimalField(decimal_places=2))) return render(request, 'wechatpay/data-group.html', {'items': object_list, 'start_time': start_time, 'end_time': end_time, 'summary': summary}) error: Traceback (most recent call last): File "D:\workspace\venv\venv-django\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "none" LINE 1: ...LECT SUM("gft_wechat_pay_wechatpay"."card_sale")::numeric(No... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\workspace\venv\venv-django\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "D:\workspace\venv\venv-django\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\workspace\venv\venv-django\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\workspace\venv\venv-django\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\workspace\weixin_pay\gft_web\gft_wechat_pay\views.py", line 249, in group_list card_recharge_sum=Cast(Sum('card_recharge'), DecimalField(decimal_places=2))) File "D:\workspace\venv\venv-django\lib\site-packages\django\db\models\query.py", … -
Update model fields based on POST data before save with Django Rest Framework
I'm using django-rest-framework and want to augment the posted data before saving it to my model as is normally achieved using the model's clean method as in this example from the django docs: class Article(models.Model): ... def clean(self): # Don't allow draft entries to have a pub_date. if self.status == 'draft' and self.pub_date is not None: raise ValidationError(_('Draft entries may not have a publication date.')) # Set the pub_date for published items if it hasn't been set already. if self.status == 'published' and self.pub_date is None: self.pub_date = datetime.date.today() Unfortunately a django-rest-framework Serializer does not call a model's clean method as with a standard django Form so how would I achieve this? -
Django: create database user on user-create
I need to implement a functionality that creates a postgres DB-user when a django-user is created in the admin interface (DB-user should have same username and password). I figured out that I could use Signals to execute a script when a user is created, but the problem is I cannot get the raw password of the user. So is there a way to get the raw password of a django user in this context? And if not, what would be the best way to implement this functionality? -
raise forms.ValidationError not working in custom template form
I have a custom template forms {% extends 'accounts/registration/base.html' %} {% block content %} {% load bootstrap3 %} <div class="container"> ` `<h1>Sign Up</h1> <form method="POST"> {{form.non_field_errors}} {% csrf_token %} <br> <input type="email" name="email" value="email"> <input type="text" name="phonenumber" value="phonenumber"> <input type="text" name="name" value="name"> <input type="password" name="password1" value="password1"> <input type="password" name="password2" value="password2"> <input type="text" name="alternavite_mobile_number" value=""> <input type="submit" class="btn btn default" value="SignUp"> </form> </div> {% endblock %} Here is my views.py file def user_signup(request): registered =False if request.POST: user_form = UserSignupForm(data=request.POST) user_pro_form = UserProfileSignupForm(data=request.POST) if user_pro_form.is_valid() and user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() user_pro = user_pro_form.save(commit=False) user_pro.user = user user_pro.save() registered = True else: raise forms.ValidationError(user_form.errors,user_pro_form.errors) else: user_form = UserSignupForm() user_pro_form = UserProfileSignupForm() return render(request,'accounts/registration/customer_signup.html') what i am getting ValidationError at /accounts/signup/ {'password2': ["Passwords don't match"], 'phonenumber': ['Enter a valid phone number.']} Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 2.0.1 Exception Type: ValidationError Exception Value: {'password2': ["Passwords don't match"], 'phonenumber': ['Enter a valid phone number.']} This is not raising error in form at instance, but on error page showing that form validation error, can you suggest me how to do it and if another simple way to use custom form template. -
Django - Website runs on localhost, returns NoReverseMatch on Ubuntu server
I'm running a project online using Django, Gunicorn and Nginx. I am currently trying to update the website by adding new URL patterns and pages for the user to view. However, this return a NoReverseMatch error whilst online, yet locally, Django doesn't return any errors. The error only occurs when the HTML file calls a namespace which I have added recently (i.e. this URL was not in the initial deployment of the website). NoReverseMatch at / Reverse for 'team' not found. 'team' is not a valid view function or pattern name. Though I have clearly specified this url and view function in the files. Thanks! -
How to clean a model form in Django?
Can someone please explain to me how I can clean all of my fields and show a custom error_message and do all of my validations on the fields ? I know how to do it with a normal Form but I do not get it how to do it with the subclass ModelForm. In my opinion there should be shown a ValidationError for title with the following code but nothing seems to happen. forms.py class AdvertisementForm(forms.ModelForm): title = forms.CharField(label="Titel", max_length=200, required=False) description = forms.CharField(label="Beschreibung", max_length=1000, widget=forms.Textarea) images = forms.ImageField( label="Weitere Bilder(max. 5)", widget=forms.ClearableFileInput( attrs={'multiple': True}) ) class Meta: model = Advertisement title, description = "title", "description" price, category = "price", "category" main_image, images = "main_image", "images" fields = [title, description, price, category, main_image, images] def clean(self): cleaned_data=super(AdvertisementForm, self).clean() title = self.cleaned_data.get("title") if not title: raise forms.ValidationError("Error") return cleaned_data views.py def advertisement_view(request): form = AdvertisementForm(request.POST or None, request.FILES or None) if form.is_valid(): print("valid") instance = form.save(commit=False) main_image = request.FILES.get("main_image") user = User.objects.get(id=request.user.id) instance.user = user instance.main_image = main_image instance.save() images = request.FILES.getlist('images') image_count = len(images) if image_count > 5: image_count = 5 for i in range(0, image_count): Image.objects.create(owner=instance, image=images[i]) return redirect("/profil/%d/" % request.user.id) else: context = { 'form': form } return … -
How to get a property from a Django model?
class Jornal(models.Model): url = models.URLField(unique = True,blank=True) name = models.CharField(max_length=100) def __str__(self): return self.name @property def domain(self): return urlparse(self.url).netloc How to I get the Jornal object through its domain? I was trying this in the shell: domain = "www.example.com" obj = Jornal.objects.get_domain(domain) and then this: domain = "www.example.com" obj = Jornal.objects(domain = domain) But none works. -
Customize Status code response from Django Rest Framework serializer
The scenario is quite straight-forward: Say i have a user model where email should be unique. I did a custom validation for this like. def validate_email(self, value): if value is not None: exist_email = User.objects.filter(email=value).first() if exist_email: raise serializers.ValidationError("This Email is already taken") return value from rest_framework response when input validation occur we should return status_code_400 for BAD_REQUEST but in this scenario we should or we need to return status_code_409 for conflicting entry. What is the best way to customize status_code response from serializer_errors validation. -
Getting human-readable value from Django's ChoiceField when nested in an ArrayField
To obtain the human readable value for a field with choices, Django provides the get_FOO_display() method. How would one go about getting the human readable values when the field is inside an ArrayField? eg: foo_array = models.ArrayField(models.CharField(choices=choices))