Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extend django admin user model with new fields?
I want to add more fields to django built in admin user model. How can I achieve it? Actually , There are three users on django server, student , teacher and parent. And by adding a 'role' field to user model, I can identify which type of user is log-ged in . So how can I extend the model field. I'm expecting to identify different role of users in login. -
GeoJSON data doesn't contain meaningful data GeoDjango
I'm using vectorformats to display GeoDjango data on my map, following this resource. I have this in my views.py file : def geojsonFeed(request): querySet = WorldBorder.objects.filter() djf = Django.Django(geodjango="mpoly", properties=['name', 'iso3']) geoj = GeoJSON.GeoJSON() s = geoj.encode(djf.decode(querySet)) return HttpResponse(s) But the response looks like this ["type", "features", "crs"] Can anyone help me identiy what's wrong with my code ? -
PasswordChangeForm is never valid, error messages always present in template
I'm trying to implement password changing functionality in my Django 2.1.7 webapp. Even when I use a GET request for the change password page, these two errors are present in the template: The two password fields didn't match. Your old password was entered incorrectly. Please enter it again. Additionally, when I POST data with the form, form.is_valid() always returns false, even though I can confirm that the error messages (the same ones listed above) are false. The form page gives no error messages unless I manually put them in. I've tried the solution here and many similar ones. As far as I can tell, my logic is the same. View def change_password(request): args = {} if request.method == "POST": form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() # Keep the user logged in after they change their password. update_session_auth_hash(request, form.user) return redirect("manager:profile") else: print("INVALID PASSWORD") print(form.error_messages) else: form = PasswordChangeForm(request.user) args["form"] = form return render(request, "manager/change_password.html", args) Template <head> {% extends 'manager/base.html' %} {% block title %} Change Password: {{ user.username }} {% endblock %} </head> {% block body %} {% if form.error_messages %} {% for error, error_message in form.error_messages.items %} <b>{{ error_message }}</b><br> {% endfor %} {% endif %} <form … -
How to add unique=true in model without overriding parent model's field? Django
I have a User model: class ExtraUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name="Is user activated?", help_text="Specifies whether user has been activated or not") email = models.EmailField(unique=True, blank=False, verbose_name="user's email", help_text='please type in your email address') # new class Meta(AbstractUser.Meta): # 103 unique_together = ("first_name", "last_name", ) Is it any way to add “unique=True” attribute to the “username” field in AbstractUser model without overriding it the same way like I did with “email” field??? It will screw autotranslation then… Somewhere in init perhaps? Thank you! -
How can i add a field to my Django model to dynamically filter a dropdown on another field?
I have a created Django-CMS Plugin with a ManytoManyField to another model. When creating the Plugin on the Front-End, i want the user to be able to filter the ManytoManyField list (which might be too long). By the way this future is already on Django admin: class ModelAdmin(admin.ModelAdmin): list_filter = ('field_name', ) form = PartnerLogoTableForm Is it possible to have something similar like that on my cms_plugins.py: class PartnerLogoTablePlugin(CMSPluginBase): model = LogoTablePlugin form = LogoTablePluginForm name = _('LogoTable Plugin') render_template = False search_fields = ('description',) def render(self, context, instance, placeholder): self.render_template = 'aldryn_logo_tables/plugins/%s/logotable.html' % instance.style context.update({ 'object': instance, 'placeholder': placeholder, }) return context plugin_pool.register_plugin(PartnerLogoTablePlugin) models.py: class PartnerLogoTable(models.Model): name = models.CharField(_('Partner name'), max_length=255) image = FilerImageField(verbose_name=_('Image'), null=True, blank=True, on_delete=models.SET_NULL) partner_url = models.TextField(_('Partner url'), null=True, blank=True, validators=[URLValidator()]) is_active = models.BooleanField(_('Is active'), blank=True, default=True) created_at = models.DateTimeField(_('Created at'), auto_now_add=True) updated_at = models.DateTimeField(_('Updated at'), auto_now=True) order = models.IntegerField(_('Order'), null=True, blank=True) class Meta: verbose_name = _('Partner Logo') verbose_name_plural = _('Partner Logos') ordering = ['order'] def __str__(self): return self.name class LogoTablePlugin(CMSPlugin): DEFAULT = 'default' LOGOTABLE_CHOICES = [ (DEFAULT, _('Default')), ] description = models.CharField(_('Description'), max_length=255, null=True, blank=True) partner = models.ManyToManyField(PartnerLogoTable, verbose_name=_('Partner')) logo_per_row = models.IntegerField(_('Logo per line'), default=1, null=True, blank=True, validators=[MaxValueValidator(4), MinValueValidator(1)], help_text=_('Number of logos to be displayed … -
How to download zip file from server side to client side (django to react)
On my django server side, I have a file that downloads some files from s3 and then zips them together. I then want to send that zip file to the client side and download it on client side. However, when ever I try to open the zip file on the client side I get a An error occurred while loading the archive I am running on Ubuntu 14.04 with a django backend and a react frontend. I tried passing the file as a tar file, but that didn't work either. I have also tried many different ways of passing the zip file to the HTMLResponse, but I always get the same error. Right now to try to make it work, I am just trying to download a zip file I have downloaded on my local computer. I have tried a bunch of different content_types from application/zip, to octet/stream and force download. django backend zip_path = '/home/konstantin/Downloads/sup.zip' content_path = mime.guess_type(zip_path) with open(zip_path, 'rb') as zip_file: response = HttpResponse(zip_file, content_type='application/zip') response['Content-Length'] = str(os.stat(zip_path).st_size) response['Content-Disposition'] = 'attachment; filename={}'.format('willthiswork.zip') return response react front end (we have a program that changes python to js). The response of the ajax call is passed directly into this … -
DRF DataTables GET Request Is Too Long
I am using DRF to serialize a model, and serve the model to an endpoint. I am using django-rest-framework-datatables to format that endpoint into the JSON DataTables requires with ?format=datatables. I have a large DataTable that I am trying to render, and once I get to a certain number of columns, a nondescript 404 error occurs. The request URL for the ajax data is 2k+ characters long, and I think this is the issue since it's a GET request. How do I get around this limitation without using POST since it's a REST API? -
Parallel Execution of Queries in Python
I am new to python-threading programming. I want to execute my Database Queries in parallel. Assuming two separate queries, how to run these in parallel to query same database, and also wait for both results to return before continuing the execution of the rest of the code? from threading import Thread, Lock class DatabaseWorker(Thread): def __init__(self, connection, query, paramDictFilter, key, query_mode, lstResultData): Thread.__init__(self) self.connection = connection self.query = query self.paramDictFilter = paramDictFilter self.key = key self.query_mode = query_mode self.lstResultData = lstResultData self.lock = Lock() def run(self): resultData = dict() try: with self.lock: with self.connection.cursor('dict') as cur: cur.execute(self.query, self.paramDictFilter) if self.query_mode == 0: resultData[self.key] = cur.fetchone() else: resultData[self.key] = cur.fetchall() cur.close() except Exception as e: print(e) self.lstResultData.append(resultData) Outside Class: connV = Database.connect_vertica_dbs() qryDefaultSection = """ """ qryBusinessAddress = """ """ workerBusinessAddress = DatabaseWorker(connV, qryBusinessAddress, paramDictFilter, "businessAddr", 1, lstResultData) workerDefaultSection = DatabaseWorker(connV, qryDefaultSection, paramDictFilter, "defaultHistory", 1, lstResultData) workerBusinessAddress.start() workerDefaultSection.start() delay = 1 while len(lstResultData) < 2: time.sleep(delay) workerBusinessAddress.join() workerDefaultSection.join() connV.close() This run only for the first time and after that it goes to infinity loop and have different attribute errors. -
Visual studio code cannot import anything from django pylint error
I have a project in django , and it is working fine. But when i changed my pc i install vscode and pylint plugin and began to appear some erros import-error. http://prntscr.com/na3r2t Anything imported from django opens this error -
How do I render a model with a different template based on a model attribute
this seems like a really basic thing, so I'm expecting this to be a straight forward answer... sorry if this is dumb. I have a model called Item. It has a headline, body text, links, etc. However, it also has an attribute 'type' which is either 'video' 'podcast' or 'article'. At the moment, I use a generic class 'DetailView' to render a detail page for Item. The template is called item_detail.html and is passed to the request from DetailView. All I want to do is have the view send a different template based on the 'type' attribute. So if item.type = 'article' render an article template, if item.type = 'video' render a video template. Is this possible whilst still using DetailView? This is what I tried in the view: class ItemDetailView(generic.DetailView): model = Item if Item.type == 'video': template_name = 'curate/item_video.html' This didn't do what I wanted - in fact the template just rendered as normal. Am I missing something? I also considered creating an entirely new model for 'videos' 'podcasts' and 'articles' but I'd rather avoid this and have an 'Item' as a powerful content type on the website. views.py class ItemDetailView(generic.DetailView): model = Item if Item.type == 'video': … -
How should I handle Django Rest Framework Unique Field Hyperlinked relationships?
I'm trying to write a custom update for DRF HyperlinkRelatedModel Serializer. But really I'm just banging my head against a wall. It throws up unique constraint errors. First I wanted to have a unique constraint on the email, that wasn't working so I removed it. Now I get the same error on the uuid field. Can someone please walk me through this, and offer some advice on handling these sorts of relationships. Below is what I have so far, it's meant to create or update a Recipient and add it to the Email. { "recipients": [ { "uuid": [ "recipient with this uuid already exists." ] } ] } Models class Recipient(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=255) email_address = models.EmailField() class Email(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) subject = models.CharField(max_length=500) body = models.TextField() recipients = models.ManyToManyField(Recipient, related_name='email') Serializers from rest_framework import serializers from rest_framework.exceptions import ValidationError from schedule_email.models import Recipient, Email, ScheduledMail class RecipientSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Recipient fields = ('url', 'uuid', 'name', 'email_address', 'recipient_type') extra_kwargs = { 'uuid': { 'validators': [], } } class EmailSerializer(serializers.HyperlinkedModelSerializer): recipients = RecipientSerializer(many=True, required=False) class Meta: model = Email fields = ('url', 'uuid', 'subject', 'body', 'recipients', 'delivery_service') def create(self, validated_data): recipient_data = … -
How to relate different attributes of user model to a different model
I'm making a Query Portal for my college and it has a complain form having different fields like First_name,Last_name,email etc.How can I fetch values of fields like First_name, Last_name, email from already saved user model fields. Complain Model from django.db import models from datetime import date from django.contrib.auth.models import User class complain(models.Model): Username = models.ForeignKey(User,on_delete=models.CASCADE) First_name=models.CharField(max_length=30) Last_name=models.CharField(max_length=30) Roll_no=models.CharField(max_length=30) Email_address=models.EmailField(max_length = 100,verbose_name='email address',blank=False,) FIRST = '1st' SECOND = '2nd' THIRD = '3rd' FOURTH = '4th' Hostel=((FIRST, 'First'),(SECOND, 'Second'),(THIRD, 'Third'), (FOURTH, 'Fourth'),) Hostel=models.CharField(max_length=3,choices=Hostel,default=FIRST,) Room_no=models.CharField(max_length=10) ACADEMIC = 'Academic' HOSTEL = 'Hostel' SPORTS= 'Sports' RAGGING = 'Ragging' ComplainDepartment=((ACADEMIC, 'Academic'),(HOSTEL, 'Hostel'),(SPORTS, 'Sports'),(RAGGING, 'Ragging'),) ComplainDepartment=models.CharField(max_length=100,choices=ComplainDepartm ent,default=HOSTEL) Complain_Subject = models.CharField(max_length = 100,default = "complain_subject") ACADEMIC_HEAD = 'Mr.J' HOSTEL_HEAD = 'Mr.Y' SPORTS_HEAD = 'Mr.Z' RAGGING_HEAD = 'Mr.W' DepartmentHead=((ACADEMIC_HEAD, 'Mr.J'),(HOSTEL_HEAD, 'Mr.Y'),(SPORTS_HEAD, 'Mr.Z'),(RAGGING_HEAD, 'Mr.W'),) DepartmentHead=models.CharField(max_length=10,choices=DepartmentHead,default=ACADEMIC_HEAD) ACADEMIC_HEAD_EMAIL = 'it1530@cemk.ac.in' HOSTEL_HEAD_EMAIL = 'it1531@cemk.ac.in' SPORTS_HEAD_EMAIL = 'it1525@cemk.ac.in' RAGGING_HEAD_EMAIL = 'w.w5@gmail.com' E_O_H=((ACADEMIC_HEAD_EMAIL, 'it1530@cemk.ac.in'),(HOSTEL_HEAD_EMAIL, 'it1531@cemk.ac.in'),(SPORTS_HEAD_EMAIL, 'it1525@cemk.ac.in'),(RAGGING_HEAD_EMAIL, 'w.w5@gmail.com'),) E_O_H=models.CharField(max_length=100,choices=E_O_H,default=ACADEMIC_HEAD_EMAIL) ComplainDescription=models.TextField(max_length=500) ComplainDate=models.DateField(("Date"), default=date.today) NOTVISITED = 'NV' VISITED = 'V' INPROCESS= 'IP' COMPLETED = 'C' Status=((NOTVISITED, 'Not Visited'),(VISITED, 'Visited'),(INPROCESS, 'Inprocess'),(COMPLETED, 'Completed'),) Status=models.CharField(max_length=2,choices=Status,default=NOTVISITED) def __str__(self): return self.Name Complain Form from django.forms import ModelForm from shp.models import * class complainform(ModelForm): class Meta: model=complain fields= ['Name','Roll_no','Email_address','Hostel','Room_no','ComplainDepartment','Complain_Subject','DepartmentHead','E_O_H','ComplainDescription','ComplainDate','Status'] -
Querying Querysets in Django? Attempting to return a step and then the sub-steps underneath it
I'm thinking this is actually really intuitive, but I cannot figure it out. So I have a model called SWS_Document. Then I have SWS_Document_Step that has a foreign key to SWS_Document. Following that I have a 3rd model SWES_Step which has a foreign key to SWS_Document_Step. Essentially SWES_Document_Step is a sub-step to SWS_Document_Step. Example. It would be "Mix the butter into the recipe" would be SWS_Document_Step. While SWES_Document_Step__id=1 would be "Place the butter into a microwave safe bowl." SWES_Document_Step__id=2 would be "Microwave the butter for 30 seconds." Those are sub-steps to "mix the butter into the recipe." class SWS_Document(models.Model): machines = models.ManyToManyField(Machine, related_name='SWS_documents') document_description = models.CharField(max_length=150, default="") pub_date = models.DateTimeField(auto_now=True) class SWS_Document_Step(models.Model): STEP_TYPE_CHOICES = ( ('People', 'People'), ('Quality', 'Quality'), ('Velocity', 'Velocity'), ('Cost', 'Cost'), ) document_number = models.ForeignKey(SWS_Document, on_delete=models.CASCADE) sws_sequence_number = models.PositiveIntegerField(editable=True, null=True) class SWES_Step(models.Model): STEP_TYPE_CHOICES = ( ('People', 'People'), ('Quality', 'Quality'), ('Velocity', 'Velocity'), ('Cost', 'Cost'), ) sws_document_id = models.ForeignKey(SWS_Document_Step, on_delete=models.CASCADE, null=True) swes_description = models.CharField(max_length=500) swes_step_type = models.CharField(max_length=8, choices=STEP_TYPE_CHOICES, blank=True) pub_date = models.DateTimeField(auto_now=True) So in my view.py I have taken swsallsteps. def DocumentView(request, document_id): # final goal should be to pass a list full of lists... # e.g. [ #[name1, [hazard1, hazard2], [assessment1, assessment2]], #[name2, [hazard3, hazard4], [assessment3, assessment4]], #] steps … -
I'm getting error false is nor true in the django tutorial
I'm following the django tutorial [here][1] https://simpleisbetterthancomplex.com/series/2017/09/25/a-complete-beginners-guide-to-django-part-4.html#testing-the-template-tags. I'm getting these errors: ====================================================================== FAIL: test_redirection (accounts.tests.test_view_signup.SuccessfulSignUpTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Inetpub\wwwroot\myproject2\myproject2\accounts\tests\test_view_signup .py", line 50, in test_redirection self.assertRedirects(self.response, self.home_url) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\test\tes tcases.py", line 283, in assertRedirects % (response.status_code, status_code) AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302) ====================================================================== FAIL: test_user_authentication (accounts.tests.test_view_signup.SuccessfulSignUp Tests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Inetpub\wwwroot\myproject2\myproject2\accounts\tests\test_view_signup .py", line 63, in test_user_authentication self.assertTrue(user.is_authenticated) AssertionError: False is not true ====================================================================== FAIL: test_user_creation (accounts.tests.test_view_signup.SuccessfulSignUpTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Inetpub\wwwroot\myproject2\myproject2\accounts\tests\test_view_signup .py", line 53, in test_user_creation self.assertTrue(User.objects.exists()) AssertionError: False is not true ---------------------------------------------------------------------- Ran 29 tests in 1.437s FAILED (failures=3, errors=1) The problem seems to be with my test_view_signup.py page. Can anyone discern what I've done wrong please? from django.contrib.auth.models import User from django.urls import reverse from django.urls import resolve from django.test import TestCase from ..views import signup from ..forms import SignUpForm class SignUpTests(TestCase): def setUp(self): url = reverse('signup') self.response = self.client.get(url) def test_signup_status_code(self): self.assertEquals(self.response.status_code, 200) def test_signup_url_resolves_signup_view(self): view = resolve('/signup/') self.assertEquals(view.func, signup) def test_csrf(self): self.assertContains(self.response, 'csrfmiddlewaretoken') def test_contains_form(self): form = self.response.context.get('form') self.assertIsInstance(form, SignUpForm) def test_form_inputs(self): self.assertContains(self.response, '<input', 5) self.assertContains(self.response, 'type="text"', 1) self.assertContains(self.response, 'type="email"', 1) self.assertContains(self.response, 'type="password"', 2) class … -
Unable to Sync already Existed Plans in Djstripe
When I add a new Product using the Stripe Dashboard I can see the webhook call come through, I can see the event "product.created" added in Django however whenever i made change in already existed plans and product, djstripe is unable to update the already existed row of that plan. I'm already running the command python manage.py djstripe_sync_plans_from_stripe after each time i update any plan/product or create any new plan/product -
Cover the text field with a choices in 'forms.ModelForm'. Django
I use my model in many forms. I would like somebody to enter text in a different choice. How can I do this for the model.Forms class in Django? My models.py class Person(models.Model): name = models.CharField(max_length=100) forms.py CHOICES = ( ('x', 'x'), ('1', '1'), ('2', '2') ) class MyForm(forms.ModelForm): class Meta: model = Person fields = ('name') # What to add to use the equivalent 'name = forms.ChoiceField(choices=CHOICES)' but without using it in the model? So, how to cover the text field with the choices in 'forms.ModelForm'. Any help will be appreciated. -
Connection between Angular and Django on POST
When I do a PUT or PATCH request from Angular to Django I receive a 200 code response. But really there are no changes in the database. The API is a Django REST API using DRF. When I do any request from Postman, all works fine. But when I try to do the request in Angular, the API response with 200 code but there are no change in the database. The same request with the same params on Angular let headers = new HttpHeaders( { 'Authorization': 'Token ' + this._userService.getToken(), 'Content-Type': 'application/x-www-form-urlencoded' } ); return this._http.patch( this.urlAPI, json , {headers: headers} ); //json is the object that I would to modify Then I tried to debug how is the object that Django receive when I send the data in Angular and in Postman and this is the difference. Probably it's the main fault but I don't know how send the data. If i try to change the Content-Type to JSON, I receive a '400 Bad Request' response. The postman output: <QueryDict: {'address': ['Some Address']} > And the Angular output: <QueryDict: {'{"address":"Some Address"}': ['']} > So I'm really lost. -
Manage.py is exiting without any output
I am attempting to upgrade a django 1.10 project to 2.2. My environment is Ubuntu 16.04 and Python 3.5.2 Django is now 2.2 and is running under gunicorn 1.19 with PostgreSQL and Redis. So far, I have removed all the versions flags from the requirements.txt, and re-installed everything using pip. I'm working in a vagrant environment, so I'm rebuilding the whole vm every time I make any changes to the config. When I try and start Gunicorn it seems to work, but looking at the logs I can see the workers are constantly starting and dying without logging anything either in log files or the console. I'm now trying to run manage.py directly and I see it just exit without any exceptions, crash logs or similar. I know it's at least parsing the settings.py - I can make it crash deliberately and I see the exception as expected. I've tried debugging with pdb - and it leads me to believe that it's crashing trying to import a module, but I'm not getting any information about which module. pdb also suggests that the manage.py is terminating with a sys.exit() - no error code, but I can't get any more information. I've … -
local svg image not found when web page loaded
I have been trying to add an svg image to my django website for awhile now. However, I keep getting this error: GET http://localhost:8000/images/enter.svg 404 (Not Found) This is what I wrote <img src='/images/enter.svg'> and my folder structure is as such index.html - images -- enter.svg I've been googling around but I can't find a solution. I hear people copying and pasting the 'data' of the svg instead, but I haven't been able to find an example. Just in case it's actually useful, here's the data of the svg image I'm trying to attach to my page: <?xml version="1.0"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.0//EN' 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'> <svg fill-opacity="1" xmlns:xlink="http://www.w3.org/1999/xlink" color-rendering="auto" color-interpolation="auto" text-rendering="auto" stroke="black" stroke-linecap="square" stroke-miterlimit="10" shape-rendering="auto" stroke-opacity="1" fill="black" stroke-dasharray="none" font-weight="normal" stroke-width="1" xmlns="http://www.w3.org/2000/svg" font-family="&apos;Dialog&apos;" font-style="normal" stroke-linejoin="miter" font-size="12" stroke-dashoffset="0" image-rendering="auto"> <!--Unicode Character 'DOWNWARDS ARROW WITH CORNER LEFTWARDS' (U+21B5)--> <defs id="genericDefs" /> <g> <g> <path d="M159.3281 330.8906 L76.6406 330.8906 Q92.5312 348.75 99.4219 368.8594 L89.2969 368.8594 Q69.6094 340.1719 34.5938 327.375 L34.5938 320.4844 Q69.6094 307.6875 89.2969 279 L99.4219 279 Q92.5312 299.25 76.6406 317.1094 L145.4062 317.1094 L145.4062 215.7188 L159.3281 215.7188 L159.3281 330.8906 Z" stroke="none" /> </g> </g> </svg> -
Django: Combining forms in Admin Panel
I have a Django's default UserCreationForm to add a new user via Admin app. I want to add new fields from another model called UserProfile. The UserProfile has a One-to-One relationship with Django's User model. The additional fields which UserProfile model has are phone number, company name etc. Is there a way where I can merge UserProfile form with Django's default User form? I looked at Django's documentation here on Inline forms but seems their require foreign key relationship. Django 2.1 -
How do I fix IntegrityErrors during the Django TestCase teardown?
I'm porting a large webapp from Python 2.7 to Python 3.6. I have managed the database migrations and converted the code using 2to3, but I'm having problems running my testing suite. For a large number of tests, I get errors like so: 62 self = <django.db.backends.utils.CursorWrapper object at 0x7fc7d0abbeb8> 63 sql = 'SET CONSTRAINTS ALL IMMEDIATE', params = None 64 65 def execute(self, sql, params=None): 66 self.db.validate_no_broken_transaction() 67 with self.db.wrap_database_errors: 68 if params is None: 69 > return self.cursor.execute(sql) 70 E psycopg2.IntegrityError: insert or update on table "probex_historicalproject" violates forei gn key constraint "probex_historicalpro_history_user_id_88371c5c_fk_auth_user" 71 E DETAIL: Key (history_user_id)=(303) is not present in table "auth_user". 72 73 ../../venv3/lib/python3.6/site-packages/django/db/backends/utils.py:62: IntegrityError 74 75 The above exception was the direct cause of the following exception: 76 77 self = <django.test.testcases.TestCase testMethod=__init__> 78 79 def _post_teardown(self): 80 """Performs any post-test things. This includes: 81 82 * Flushing the contents of the database, to leave a clean slate. If 83 the class has an 'available_apps' attribute, post_migrate isn't fired. 84 * Force-closing the connection, so the next test gets a clean cursor. 85 """ 86 try: 87 > self._fixture_teardown() 88 89 ../../venv3/lib/python3.6/site-packages/django/test/testcases.py:925: 90 _ _ _ _ _ _ _ _ _ _ _ _ … -
Form not validation failed on hitting the url twice
I have one model form for entering product detail. After submitting it I am validating this form in a view and returning another HTML page. It is working fine. Now on another page, where I am coming after submitting the form, I am doing 2 things: 1. Refreshing the page by clicking on the refresh icon: In this case, validation is happening as usual. I am facing a problem when I am doing this 2nd thing: When I hit the same URL again then the form validation is failing. Why? Can anyone please help me? Url for getting the form: /createProduct Url for submitting the form: /saveProduct This is my model form: #Model form for Product model class ProductForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'class':'form- control','placeholder':'Product Name','name':'product-name'})) category = forms.ModelChoiceField(widget=forms.Select(attrs={'class':'form-control','selected':'Select Product Category','name':'product-category'}),queryset=Category.objects.all()) description = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Product Description','name':'product-description'})) price =forms.DecimalField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Product Price','name':'product-price'})) contact =forms.IntegerField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Provide your contact no','name':'poster-contact'})) class Meta: model = Product #fields = ('name','category', 'image','description','price') fields = ('name','category','description','price','contact') This is the view for rendering product form: def create_product_fn(request): form = ProductForm() return render(request, 'olx/product/create_product.html', {'form': form}) This is the view where I am coming after submitting the form: def save_new_product(request): if request.user.is_authenticated: formToSave = ProductForm(request.POST,request.FILES) if formToSave.is_valid(): # Instead of saving it store it in … -
Local domain for django through nginx-proxy in docker
I am running a django graphene GraphQL API in a docker container exposed at port 8080. I have also setup the django-hosts package for subdomains. Now I want them to be accessible locally. It perfectly works when I add each subdomain to my hosts file on windows like this: 127.0.0.1 www.mysite.local 127.0.0.1 api.mysite.local And when I call e.g. api.mysite.local:8080. In that case I would need to add every subdomain to my hosts file, for which reason I was looking at nginx-proxy. So my hosts file now contains: 127.0.0.1 mysite.local For making sure it works I have tried it with a simple static web page like that: version: '3.7' services: nginx-proxy: image: jwilder/nginx-proxy ports: - "80:8080" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro web: image: nginx volumes: - ./html:/usr/share/nginx/html ports: - "8080:80" environment: - VIRTUAL_HOST=mysite.local - NGINX_PORT=80 That perfectly works, but trying that for my django application does not: version: '3.7' services: django: build: context: . dockerfile: Dockerfile working_dir: /app environment: - PYTHONUNBUFFERED=1 - VIRTUAL_HOST=*.mysite.local - VIRTUAL_PROTO=uwsgi ports: - 8080:8080 ... So I have added a wildcard flag such that the nginx-proxy can handle the django subdomains. The domain http://api.mysite.local is not there. What am I missing? -
How to pass a key of dictionary into anchor tag in django template?
I have this following dictionary: results[calendar.month_name[date_cursor.month]] = [e,z] In my template: {% for key, value in data %} <tr> <td><center><a href="{% url 'stockkeeping:purchase_datewise' pk=company_details.pk month={{ key }} pk3=selectdatefield_details.pk %}"></a>{{ key }}</center></td> {% if value.0 == 0 %} <th><center></center></th> {% else %} <td><center>{{ value.0 }}</center></td> {% endif %} <th><center></center></th> {% if value.1 == 0 %} <th><center></center></th> {% else %} <td><center>{{ value.1 }} Dr</center></td> {% endif %} </tr> {% endfor %} When I try to do month={{ key }} It throws me a error like this Could not parse the remainder: '{{' from '{{' Can anyone tell me how to pass the value of key in my template. Thank you -
ModuleNotFoundError: No module named 'django' , but django is installed
I am installing Django. Following commands were executed successfully: pipenv install djangorestframework pipenv shell django-admin startproject api_example cd api_example This command: python manage.py migrate Gives these error: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'