Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to log out by deleting token
''' like this class UserLoginViewSet(viewsets.ViewSet): def create(self,request): try: data=request.data email=data.get('email') password=data.get('password') date_of_birth=data.get('date_of_birth') if not all([email,password,date_of_birth]): raise Exception('all fields are mandetory') user=authenticate(username=email,password=password) if user is not None: token=generate_token() user_info=MyUser.objects.get(email=email) data=({ 'email':user_info.email, 'password':user_info.password, #'data_of_birth':user_info.data_of_birth }) return Response({"message": "You are successfully logged in", "user_info":data,"token": token, "success": True},status=status.HTTP_200_OK) else : raise Exception('not authorised') except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) def delete(self,request): logout(request) return Response({'successfull':True}) my user is logging out correctly,but i want to doi this by deleting token , -
Django configuration issue
I have installed Django and able to run the server and access the Django home page. But when I add the model class I am getting the following error in terminal. RuntimeError: Model class myproject.urls.Board doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. This is my code in settings.py ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'boards', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pythondb', 'USER' : 'root', 'PASSWORD' : 'calpine', 'HOST' : 'localhost', 'PORT' : '3306', } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' Model Class from django.db import models from django.contrib.auth.models import … -
How to access one to many relationship grouped by instance within a for loop in a django template
im facing a really tough issue that im unable to resolve. I have been tasked to generate a table with very specific order , which is the root of my problem as the way it is written does not make sense in terms of a relational database. To illustrate my problem , here is my code. This is the relavant part of my template : {%for item in itemdetails%} <tr> <td style="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" height="15" align="left" valign=top colspan=2 ><font face="Arial">{{forloop.counter}} {{item.description}}<br></font></td> <td style="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-right: 1px solid #000000" align="left" valign=middle><font face="Arial" color="#000000">{{item.code}}<br></font></td> <td style="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" align="center" valign=middle><font face="Arial" color="#000000"><br></font></td> {%for trial in trial%} {%for detail in trial.itemdetails_set.all%} <td style="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" align="center" valign=middle><font face="Arial" color="#000000">{{detail.percent}}<br></font></td> {%endfor%} {%endfor%} </tr> {%endfor%} This is my view( i have set this to query a specific ProductFormulation instance , this will be changed to filter it dynamically in the future) : def summary(request): if hasattr(request.user, 'salesextra'): context = { … -
session key is not found over was not accessible
File "D:\mysite\source\accounts\views.py", line 31, in from .storage_loc import UserStorage File "D:\mysite\source\accounts\storage_loc.py", line 16, in class UserStorage(S3Boto3Storage): File "D:\mysite\source\accounts\storage_loc.py", line 18, in UserStorage use = us.getitem('user') File "D:\mysite\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 64, in getitem return self._session[key] KeyError: 'user Storage_loc.py class UserStorage(S3Boto3Storage): us = SessionStore() use = us.__getitem__('user') location = 'users/%s' % use file_overwrite = False forms.py class SignInViaEmailForm(SignIn): email = forms.EmailField(label=_('Email')) @property def field_order(self): if settings.USE_REMEMBER_ME: return ['email', 'password', 'remember_me'] return ['email', 'password'] def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('You entered an invalid email address.')) if not user.is_active: raise ValidationError(_('This account is not active.')) self.user_cache = user s = SessionStore() s['user'] = email s.save() return email -
Unable to send a message to the user in the django-private-chat integrated in the application?
I am a newbie to django and I am doing an application which needs one to one messaging I had integrated the django-private-chat in my application by following the steps in the documentation https://readthedocs.org/projects/django-private-chat/downloads/pdf/latest/ and now I am unable to send a message to the users please help me out what should I do other than that specified in this documentation to send and receive messages in real time I also had run this command python manage.py run_chat_server even though I am not getting please help me -
Image not closing because function is still using it
I have a save method that looks like this: def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) if self.avatar: image = Image.open(self.avatar) image_path = self.avatar.path image_name = self.avatar.path[:-4] image_ext = self.avatar.path[-4:] resize_images(image, image_path, image_name, image_ext) image.close() When I trigger the save method once, it works. However, when I trigger it again I get an error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: xxxx I have an overwrite method that will go in and clean the directory and then save the new image. However, since the previous image did not close yet and it's still in "use" it's giving this error. When I remove the resize_images method, everything works and I don't get the error. This is how resize_images looks like: def resize_images(image, image_path, image_name, image_ext): image = image.resize((400, 400), Image.ANTIALIAS) image.save(image_path, optimize=True, quality=95) medium_image = image.resize((250, 250), Image.ANTIALIAS) image.close() medium_path = image_name + "_medium" + image_ext medium_image.save(medium_path, optimize=True, quality=95) small_image = medium_image.resize((100, 100), Image.ANTIALIAS) small_path = image_name + "_small" + image_ext small_image.save(small_path, optimize=True, quality=95) medium_image.close() mini_image = small_image.resize((50, 50), Image.ANTIALIAS) mini_path = image_name + "_mini" + image_ext mini_image.save(mini_path, optimize=True, quality=95) small_image.close() mini_image.close() So basically what happens is user uploads profile picture, … -
Getting "value must be an integer" when running my Django seeds YAML file
I'm using Django 2.0, Python 3.7, and MySql 5.5. I have this model, from which I generated my SQL migration ... class CoopType(models.Model): name = models.CharField(max_length=200, null=False) class Meta: unique_together = ("name",) I then have this in my seeds_data.yaml file ... - model: maps.cooptype pk: 11 fields: name: "Coworking Space" Upon attempting to run my seeds file, it dies with this error ... python manage.py loaddata maps/fixtures/seed_data.yaml ... django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/davea/Documents/workspace/chicommons/maps/maps/maps/fixtures/seed_data.yaml': ["'{'pk': 11, 'name': 'Coworking Space'}' value must be an integer."]: (maps.coop:pk=1) field_value was '{'pk': 11, 'name': 'Coworking Space'}' I'm confused by the error because it would appear the primary key is an integer so what is the error talking about? -
Access django runserver from external
I setup local server python manage.py runserver,then confirmed it works successfully wget http://127.0.0.1:8000 And setup iptables, but can not connect yet. I checked net setting around and this is netstat -nap Other port 22,25,993,995 etc.... is accessed from external, but 8000 is not possible, I guess it is because only 8000 has this parameter 127.0.0.1:8000 Where can I set? $sudo netstat -nap Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1413/sshd tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN 1887/master tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN 21651/python tcp 0 0 0.0.0.0:993 0.0.0.0:* LISTEN 1788/dovecot tcp 0 0 0.0.0.0:995 0.0.0.0:* LISTEN 1788/dovecot tcp 0 0 0.0.0.0:587 0.0.0.0:* LISTEN 1887/master tcp 0 0 0.0.0.0:110 0.0.0.0:* LISTEN 1788/dovecot tcp 0 0 0.0.0.0:24622 0.0.0.0:* LISTEN 1466/vsftpd tcp 0 0 0.0.0.0:143 0.0.0.0:* LISTEN 1788/dovecot -
adding products and quantity to an invoice in django
First of all, I am very new to Django and Python and I'm struggling trying to make an VERY simple invoice to work. I have 3 classes; Provider, Product and Invoice. Product and Provider work just fine, I am able to fill them out and they get saved in the database, the thing now is I need to fill an Invoice, selecting a Provider, Products (one or many) and filling the quantity for each product. What I can't seem to find out how to do is: add a quantity to each product selected (I have no clue how to do that) and calculate the total (I know I should be multiplying prices and quantities and then summing them up but I don't know where to do that and how to save it). I tried adding a LineItem class but I couldn't make it work either. I'm using Python 3.7 and Django 3.0 I'm sending the code I wrote so far. (just in case: Proveedor=Provider, Producto=Product, Factura=Invoice, cantidad=quantity, precio=price) Thank you in advance! models.py class Proveedor(models.Model): apellido = models.CharField(max_length=200, null=True) nombre = models.CharField(max_length=200, null=True) cuit = models.CharField(max_length=13, null=True) teléfono = models.CharField(max_length=200, null=True) dirección = models.CharField(max_length=200, null=True) def __str__(self): return '{} {}'.format(self.nombre, … -
ListView has stopped working since adding Slug field to model
In trying to fix one problem I managed to prevent ListView from working. I tried Googling the problem but got thousands of pages of theory and unfortunately no actual guidance. class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] I added these lines of code to the model which has caused the problem. url= models.SlugField(max_length=500, unique=True, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super(UserPost, self).save(*args, **kwargs) models.py Update - I have tried to add a SlugField based on Pedros comment. class Post(models.Model): title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) url= models.SlugField(max_length=350, unique=True, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super(UserPost, self).save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=40) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) -
Django.core.exceptions.ImproperlyConfigured: Error running functional_tests.py
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. my functional tests: from selenium import webdriver from lists.models import Item from selenium.webdriver.common.keys import Keys import time import unittest import os class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): self.browser.get('http://localhost:8000/') # She notices the page title and header mention to-do lists print(self.browser.title) self.assertIn('lists', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('list', header_text) inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual( inputbox.get_attribute('placeholder'), 'Enter a to-do item' ) inputbox.send_keys('Buy peacock feathers') inputbox.send_keys(Keys.ENTER) time.sleep(1) table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertIn('1: Buy peacock feathers',[row.text for row in rows]) self.assertIn('2: Use a peacock feather', [row.text for row in rows]) self.fail('Finish the test!') def check_for_row_in_list_table(self,row_text): table = self.browser.find_element__by_id('id_list_table') rows = table.find_element_by_tag_name('tr') self.assertIn(row_text,[row.text for row in rows]) inputbox.send_keys(Keys.ENTER) time.sleep(1) self.check_for_row_in_list_table('1:Buy a peacock feather') inputbox = self.browser.find_element_by_id('id_new_item') input.send_keys('Use peacock feathers to make a fly') inputbox.send_keys(Keys.ENTER) time.sleep(1) self.check_for_row_in_list_table('1:Buy a peacock feather') self.check_for_row_in_list_table('2: Use a peacock feather') if __name__ == '__main__': unittest.main(warnings='ignore') my models :When I try to run functional_tests I get the error. from django.db import models class Item(models.Model): text = models.TextField(default='') my settings file . I have included the list app in my INSTALLED_APPS too. import os … -
Django url changes
I was working on a blog app in Django and I kept encounter this error. When I am want to go to the a specific article then then the url shows this: http://localhost:8000/article/dubstech But when I want to change from that article to another part of the website this is what happens http://localhost:8000/article/calender When in the website it should be: http://localhost:8000/calender HTML <section class="pt-5 pl-5"> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for article in articles %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ article.title }}</h2> <p class="card-text text-muted h6"> <img src="article/{{ article.upload_image }}"> | {{ article.author }} | {{ article.created_on | date}} </p> <p class="card-text">{{article.content|slice:":200" }}</p> <a href="article/{{ article.slug }}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% endfor %} </div> </div> </div> </section> python urlpatterns = [ path('', views.home, name="Hompeage"), path('article/<slug:slug>', views.article, name="Article"), path('resources', views.resources, name="Resources"), path('mosquemap', views.mosquemap, name="MosqueMap"), path('community', views.community, name="Community"), path('calender', views.calender, name="Calender"), ] def article(request, slug): article = Post.objects.filter(slug=slug).values() related_articles = Post.objects.get(slug=slug) article_info = { "article": article, "related_articles" : related_articles.tags.similar_objects(), # Instance of Post is article } return render(request, 'article.htm', article_info) -
assertRaises context manager doesn't raise exception
Within one of my models I have defined a clean method that is suppose to raise a ValidationError. models.py class Menu(models.Model): season = models.CharField( max_length=20, unique=True ) items = models.ManyToManyField('Item', related_name='items') created_date = models.DateTimeField( default=timezone.now) expiration_date = models.DateTimeField( blank=True, null=True) def __str__(self): return self.season def clean(self): if self.created_date > self.expiration_date: raise ValidationError({ 'expiration_date': "The expiration date is set before the created date" }) The test written for this case is using assertRaises() as a context manager. Upon running the test, I get the error: test_forms.py def test_menu_model_clean(self): with self.assertRaises(ValidationError): self.menu_form.full_clean() self.menu_form.full_clean() AssertionError: ValidationError not raised However the test passes if it is written as the following: def test_menu_model_clean(self): self.assertRaises(ValidationError, self.menu_form.full_clean()) Why is the test failing as written as a context manager? -
Django File upload error in Heroku Deployment
I have made a regular django website for my college that lets user sign in, sign out and lets them upload notes(documents) that can then be downloaded. I have deployed the django app on heroku free tier. Everything works fine till a user logs in and tries to upload the document. The website is deployed here. Please feel free to use the app and uploading a test document and to address the issue. I have tried debugging with no luck sadly. Here's the TL;DR code that I guess is causing the problem. Source code at github # models.py class Notes_Model(models.Model): uploader = models.CharField(max_length=200) title = models.CharField(max_length=200) date_posted = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=2500) branch_choice = models.CharField(max_length=50, choices=branch_choices, default='cse') file_semester = models.CharField(choices=semester_choice, max_length=2) file = models.FileField() def __str__(self): return self.title def get_absolute_url(self): return reverse("notes-detail", kwargs={"pk": self.pk}) # views.py class PostCreateView(LoginRequiredMixin, CreateView): """ Lets user upload files under the UPLOAD navigation button """ model = Notes_Model fields = ['title', 'description', 'file_semester', 'branch_choice', 'file'] @login_required def upload_file(self, request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, f'Your files have been uploaded') return redirect('notes-home') def form_valid(self, form): form.instance.uploader = self.request.user # form.save() return super(PostCreateView, self).form_valid(form) # settings.py DATABASES = { "default": … -
Calculate intersection of two Django queries: one aggregate, another - simple
I have a model VariantTag that stores the ids of another model called SavedVariant. The former has another variant_tag_type_id that is pointing to its relative model type VariantTagType. Now I am trying to get all SavedVariant ids which have only one variant_tag_type.name = 'Review' tag. To make things clearer here is what I am trying to do in Django: # Variants with just only one tag present single_variant_ids = VariantTag.objects.values_list('saved_variant_id', flat=True) \ .annotate(id_count=Count('saved_variant_id')).filter(id_count=1) # All variants that have 'Review' tag review_all_variant_ids = VariantTag.objects.filter(variant_tag_type__name='Review') \ .values_list('saved_variant_id', flat=True) # Intersection of the previous two queries review_variant_ids = single_variant_ids.intersection(review_all_variant_ids) And this is not working giving me an error: ProgrammingError: each INTERSECT query must have the same number of columns LINE 1: ...nttag"."saved_variant_id") = 1) INTERSECT (SELECT "seqr_vari... How could I write such a query in Django? -
dispatch() missing 1 required positional argument: 'slug'
I am getting the error dispatch() missing 1 required positional argument: 'slug'. I have tried def dispatch(self, request, slug=none, *args, **kwargs): and def dispatch(self, request, slug=title, *args, **kwargs):. I want people to be able to add comments to posts. I have tried a variety of experiments (including the few I listed above) and every experiment leads to an error message I cannot resolve. views.py class PostDetailView(DetailView): model = Post def dispatch(self, request, slug, *args, **kwargs): post = get_object_or_404(Post) comments = post.comments.filter(active=True, slug=slug) new_comment = None if request.method == 'POST': abc else: xyz models.py class Post(models.Model): title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=30) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) -
Django template: condition check with previous object
I need check the condition with previous object in loop. (previous_object) is for illustration only. {% for object in objects %} {% if (previous_object).clicks == 0 %} #this reference must be based on the loop's previous object. <button type="submit"> OK </button> {% endif %} {% endfor %} Does anyone have any ideas? Thanks! -
Django: Proper Way to Acess data from a One to Many Relationship?
I am having issues with accessing data through a django one to many relationship. After 3 painstaking days I figured out a way to display the data from the relationship by overriding the get_context_data method. I was wondering if that was the proper way to do it. This works but I could imagine that there is a better way to do this that I missed in the documentation. Here is the code for that: class QuestionDetailView(DetailView): model = Question def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['answers'] = Answer.objects.filter(firm=context['object']) return context Here is the code for the models: class Question(models.Model): text = models.CharField(max_length=120, unique=True) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) Here is the code in my template: {% extends "base.html" %} {% block body %} <div class=""> <h3>{{ object.text }}</h3> <p>Answers:</p> <ul> {% for answer in answers %} <li> {{ answer }}</li> {%empty%} <li>No answers</li> {% endfor %} </ul> </div> {% endblock %} -
Using a formset to create links to records
I'm using Django version 3.0.1, python version 3.6.9 I am trying to set urls to individual records in a loop inside a formset but the url tag can't see my variable even though it is printed out in the first table cell before I add the second line : {# This displays correctly the integer id #} <td>{{ form.record_id.value }}</td> {# This next line doesn't work, though the above TD does display the record_id #} <td><a href="{% url 'record_detail' form.record_id.value %}">{{ form.name.value }}</a></td> The error I get is this as the page is rendered: Reverse for 'record_detail' with arguments '(None,)' not found. 1 pattern(s) tried: ['myapp\\/record_detail\\/(?P<pk>[0-9]+)\\/$'] This is my template table code (note the second line is commented out otherwise I get the error message on viewing the page): <table id="formset" class="form"> {% for form in recordFormset.forms %} <tr class="someclass"> <td>{{ form.record_id.value }}</td> {# This next line doesn't work, though the above TD does display the record_id #} {# <td><a href="{% url 'record_detail' form.record_id.value %}">{{ form.name.value }}</a></td> #} </tr> {% endfor %} </table> I am guessing this is because the url is created before the for loop through the formset's forms, but how then can I create these urls that … -
When I tried to run my Django server I faced the following problem
I am trying to run my Django server and I am facing the following issue. So, I am pretty new on Django, then Let me know if you need any additional information. This code is really complex to me and I am challenging myself to run multiples applications at the same time. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.2 Python Version: 3.6.4 Installed Applications: ['registration', 'mailqueue', 'el_pagination', 'social_django', 'django_inlinecss', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware'] Traceback: File "/home/rnominato/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/rnominato/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/rnominato/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rnominato/PycharmProjects/Liben_Feb_2020/main/decorators.py" in wrap 20. mode = Mode.objects.get(id=1) File "/home/rnominato/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/rnominato/anaconda3/lib/python3.6/site-packages/django/db/models/query.py" in get 408. self.model._meta.object_name Exception Type: DoesNotExist at / Exception Value: Mode matching query does not exist. -
Django UpdateView: cannot get form fields to show database values
I found multiple answers to this same questions but unfortunately, I can't seem to figure it out :( The form has a drop-down list for the 'subcategory' field in my model 'PhysicalPart', the values of the 'subcategory' field are updated dynamically upon the form creation (using a 'category' parameter). Unfortunately, I can't get the drop-down to show all subcategories AND have the one from the database selected at the same time. I can't seem to retrieve the 'short_description' value either from the database. It used to work before I learned about UpdateView class and decided to use it instead... Any insight on how-to workaround my problem would be appreciated! forms.py class PartForm(forms.ModelForm): subcategory = forms.ChoiceField(choices=[]) class Meta: model = PhysicalPart fields = ['subcategory', 'short_description'] views.py class PartUpdate(UpdateView): model = PhysicalPart template_name = 'part_update.html' form_class = PartForm def post(self, request, *args, **kwargs): # Load model instance self.object = self.get_object() # Load form form = super(PartUpdate, self).get_form(self.form_class) # Populating subcategory choices form.fields['subcategory'].choices = SubcategoryFilter[self.object.category] # Check if form valid and save data if form.is_valid(): form.save() return redirect('part-list') # Update context before rendering context = self.get_context_data(**kwargs) context['part_id'] = self.object.pk context['part_category'] = self.object.category context['manufacturing_list'] = self.object.manufacturing.all() return render(request, self.template_name, context) html <form action="{% url … -
How to create a new item in the database upon opening Django CreateView
I'm trying to auto-create an object in database in the background, upon opening a link in Django using Django generic class views, here is my code : class BuyInvoiceItemCreateView(generic.CreateView): model = models.BuyInvoiceItems fields = "__all__" def get(self, request, *args, **kwargs): models.BuyInvoice.objects.create(number=0) return render(request, "Point_of_sale/buyinvoiceitems_form.html") I've tried to override the get method, but it creates 2 objects every time I open the link instead of 1 object. -
Is there a way in a seed_data.yaml file to autogenerate models on which first model is dependent upon?
I'm using Django 2.0, Python 3.7, and MySql 5. I have the following two models, the second dependent on the first ... class CoopType(models.Model): name = models.CharField(max_length=200, null=False) class Meta: unique_together = ("name",) class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I'm creating some seed data for the second model. I was wondering if there was a way to auto-generate data for the first model from within the second model. I tried this ... - model: maps.coop pk: 1 fields: name: "1871" type: pk: null name: Coworking Space address: street_number: 222 route: 1212 raw: 222 W. Merchandise Mart Plaza, Suite 1212 formatted: 222 W. Merchandise Mart Plaza, Suite 1212 locality: name: Chicago postal_code: 60654 state: code: IL enabled: True phone: email: web_site: "http://www.1871.com/" latitude: 41.88802611 longitude: -87.63612199 but I get this error when running the seed data ... (env) localhost:maps davea$ python scripts/parse_coop_csv.py ~/Downloads/chicommons_prep.xlsx\ -\ Mapping\ Sheet.csv > maps/fixtures/seed_data.yaml (env) localhost:maps davea$ python manage.py loaddata maps/fixtures/seed_data.yaml Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 923, in to_python return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, … -
Run Django tests in the VSCode Test explorer?
I am trying to run Django unit tests in the VSCode Test Explorer, also, I want the CodeLens 'Run Tests' button to appear above each test. enter image description here However, in the Test Explorer, When I press the Play button, an error displays: "No Tests were Ran" No Tests were Ran My directory structure is: Workspace_Folder settings.json repo python_module_1 sub_module tests test_a.py I am using the unittest framework. My Settings.json looks like this: { "python.pythonPath": "/Users/nbonilla/.local/share/virtualenvs/koku-iTLe243o/bin/python", "python.testing.unittestArgs": [ "-v", "-s", "${workspaceFolder}/python_module_1/sub_module/" ], "python.testing.pytestEnabled": false, "python.testing.nosetestsEnabled": false, "python.testing.unittestEnabled": true, } When I press the green "Play" button Test Explorer Play Button The Python Test Log Output shows the message "Unhandled exception in thread started by" Unhandled Exception in thread started by I am using a pipenv virtual environment. How do I run these Django Tests in the VSCode Test Explorer? I saw that using pyTest is an alternative to unittest, how can this be set up easily as a replacement? -
User can't like his/her own comment - Django
These are my models: class Post(models.Model): class Meta: constraints = [ models.UniqueConstraint(fields=['user'], condition=Q(is_featured=True), name='unique featured post per user'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) post = models.TextField() is_featured = models.BooleanField(default=False) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) title = models.CharField(max_length=255) comment = models.CharField(max_length=500) class Like(models.Model): class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'comment'], name='unique like per comment'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) is_positive = models.BooleanField(blank=True, null=True) GOAL: I would like to add a constraint where the user can't like his own comment. I tried, but of course I can't do this: models.UniqueConstraint(fields=['user'], condition=~Q('user__id__in'=Like.objects.values_list('user_id', flat=True), name='unique like per comment'),