Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSR + CSR (?) can I add SSR to a vue-cli 3 project? (vue-cli 3 + django)
I'm using the Vue-CLI 3 and Django together. I think it might be a basic question, I can't sure that is right structure. Vue-CLI vue vue-router vuex Django (Django restframework) router (we have url.py for each page) API _base.html (_base.html included on every page, and main.js located in frontend/dist/static/main.js) <body> {{% static main.js %}} </body> It can be access every pages with SSR x CSR load vue component on routed in Vue-CLI without page loading(=CSR) when I click a link that defined router-link. Django return 404 when try to access not defined page url (e.g. GET http://localhost:8000/aaa). I would be great if you could give me some advice. thanks. -
pass serializer errors as a response in a list format
I am using graphene_django alongside rest_framework serializers. When i get validation issue, I am getting the error as follow "{'email': [ErrorDetail(string='user with this Email Address already exists.', code='unique')]}", How can I pass the error in a List way like I am passing when password do not match? here is how I am doing right now class Register(graphene.Mutation): class Arguments: email = graphene.String(required=True) password = graphene.String(required=True) password_repeat = graphene.String(required=True) user = graphene.Field(UserQuery) token = graphene.String() success = graphene.Boolean() errors = graphene.List(graphene.String) @staticmethod def mutate(self, info, email, password, password_repeat): if password == password_repeat: try: serializer = RegistrationSerializer(data={'email': email, 'password': password, 'is_confirmed': False}) print('#########Serializer########', serializer) if serializer.is_valid(raise_exception=True): print('serializer is valid') user = serializer.save() auth = authenticate(username=email, password=password) login(info.context, auth) return Register(success=True, user=user, token=get_token(auth)) print('############serializer errors##########', serializer.errors) return Register(success=False, token=None, errors=['email/password', 'Unable to login']) except ValidationError as e: print("validation error", e) return Register(success=False, errors=[e]) return Register(success=False, errors=['password', 'password is not matching']) -
High memcached connections after django upgradation
We recently upgraded our django site from 1.6 to 1.11 which is running on python2. Recently we have observed memcahed down and we have found in error log below message. [Thu Jul 25 12:56:58.342182 2019] [:error] [pid 32575:tid 140131889002240] ServerDown: error 47 from memcached_get(key): (140131092682816) SERVER HAS FAILED AND IS DISABLED UNTIL TIMED RETRY, host: localhost:11211 -> libmemcached/get.cc:314 I am using memcached default configurations and django default settings. Can any one suggest me fix for this? And best configurtation for django settings? Thanks -
CSRF token missing or incorrect - Django 2.2
I try to create an admin user in my application, but even I do not include any code, it gives the error 'CSRF token missing or incorrect'. I can't find what to do. Can anyone solve this problem? I tried all the suggestions from my friends, and Django documentation, but none of them could solve it. Actually, there is no need to paste my code, because as I mentioned before even without any HTML templates it is not possible to create an admin user. -
Django ORM leaks connections when using ThreadPoolExecutor
I'm using ThreadPoolExecutor to speed up data processing. The problem is that the thread pool creates new database connections and Django doesn't close them. I do have CONN_MAX_AGE in settings.py and I already tried to call django.db.close_old_connections(). Here is a code example: def compute(job): result = FooModel.objects.filter(...).aggregate(...) return BarModel.objects.create(result) def process(dataset): thread_pool = ThreadPoolExecutor(max_workers=20) futures = [] for job in dataset: futures += [thread_pool.submit(compute, job)] results = list(r.result() for r in wait(futures)[0]) return results for i in range(0, 100): process(['foo', 'bar', qux']) Is Django ORM able to terminate idle DB connections if they were started in another thread? -
How to get access to objects that have been deleted in Model in Django?
I am developing a parking management system in Django that records the 'Vehicle' object according to its time of entry, and calculates the value as it leaves, but I need to develop a reporting system that returns how many cars entered and how much total value of the day. How can I get access to vehicles that have left, because on my system, after the checkout, the object is deleted in the database to report in the report. # models.py class Vehicle(models.Model): brand = models.CharField(max_length=100, null=False) model = models.CharField(max_length=100, null=False) color = models.CharField(max_length=50, null=False) vehicle_plate = models.CharField(max_length=8, null=False) entry_time = models.DateTimeField(auto_now_add=True, null=False) def __str__(self): return self.vehicle_plate class Price(models.Model): morning = MoneyField(max_digits=14, decimal_places=2, default_currency='BRL', default='2') afternoon = MoneyField(max_digits=14, decimal_places=2, default_currency='BRL', default='3') weekend = MoneyField(max_digits=14, decimal_places=2, default_currency='BRL', default='2.5') def __str__(self): return "value table" I think need to create a template for registering vehicles that have left parking lot, but I don't know how to get access to deleted objects. -
UnboundLocalError at /products/search/ local variable 'query' referenced before assignment
I have this problem UnboundLocalError at /products/search local variable 'query' referenced before assignment /on this code help out, am searching a product using title and category def search(request): try: q = request.GET.get('q', '') except: q = False if q: query = q product_queryset = Product.objects.filter( Q(name__icontains=q)| Q(description__icontains=q) ) category_queryset = Category.objects.filter( Q(title__icontains=q)| Q(description__icontains=q) ) results = list(chain(product_queryset,category_queryset)) context = { 'query':query, 'product_queryset':product_queryset, 'category_queryset':category_queryset, 'results':results, } return render(request,"products/search.html", context) -
Accessing ImageField in clean()/save() at creation time and updates
I have a model in Django which has a lot of computed fields, it looks like this: class Media(models.Model): titel = models.CharField(max_length=128) datei = models.ImageField(upload_to='usermedia/%Y/') # automatically calculated fields width = models.PositiveIntegerField(editable=False) height = models.PositiveIntegerField(editable=False) imagetype = models.CharField(editable=False, max_length=32) thumbnail_b64 = models.CharField( editable=False, max_length=4096) def clean(self): self.width = self.datei.width self.height = self.datei.height self.imagetype = magic.from_buffer(self.datei.read(), mime=True) buffer = BytesIO() img = Image.open(self.datei) img.thumbnail((32, 32)) img.save(buffer, format="PNG") self.thumbnail_b64 = base64.b64encode( buffer.getvalue()).decode("utf-8") Everything is good at a first glance - the model does what is meant to, at least at adding new Instances. But as soon as I try to update one instance, then Django raises an error: Exception Type: ValueError Exception Value: read of closed file The problem seems to be self.imagetype = magic.from_buffer(self.datei.read(), mime=True). I think self.datei is no longer in the memory, right? I therefore changed the from_buffer thingy in both parts into: self.imagetype = magic.from_file(self.datei.path, mime=True) ... img = Image.open(self.datei.path) Now I can finally update my model instances, BUT now I am getting a FileNotFoundError error when adding new instances... How would a solution look like that works for both, adding new entries and updating old ones? -
How to make CORS POST requests using axios?
I can make a POST request from PostMan and successfully hit the backend. However, when I try in the react app I get: Access to XMLHttpRequest at 'http://XXX.ngrok.io/api/top_level_source_jobs/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Axios post code: axios.post(url, data, { headers: { 'Access-Control-Allow-Credentials': true, 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'application/json', } }) .then(res => { console.log(res) }) .catch(err => { console.log(err); }); For some reason, installing this app fixes it: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en What does this app do that my headers aren't? Is axios not setting headers for some reason? -
Issues getting all users from my django models
I am trying to get all the user from my database to display all the username, goals and goals id using the related name, but I can't seem to do that. model class GoalStatus(models.Model): status_name = models.CharField(max_length=60) def __str__(self): return self.status_name class ScrumyGoals(models.Model): goal_status = models.ForeignKey(GoalStatus, on_delete=models.PROTECT, related_name='goalstatus') user = models.ForeignKey(User, related_name='scrumygoals', on_delete=models.PROTECT) goal_name = models.CharField(max_length=60) goal_id = models.IntegerField() created_by = models.CharField(max_length=60) moved_by = models.CharField(max_length=60) owner = models.CharField(max_length=60) view def home(request): user = User.objects.all() # User1 = ScrumyGoals.objects.filter(goal_name='Learn Django') context = {'User': User} return render(request, 'django/home.html', context) template {% for g in User.scrumygoals_set.all %} <td>g.User.User</td>> <td>g.goal_name</td>> <td>g.goal_id</td>> {% endfor %} the output is supposed to look like this User Weekly Goals Daily Goals Verify Goals Done Goals username Goalname Goalid Goalname Goalid -
Is there a way I can render the text present in a docx/doc(that I uploaded using file field) file to an HTML template in the exact same manner?
I want to upload a specific doc file using File field And view it as an HTML text with all the bold and italics and bullets and indents originally present in the doc file. Is it possible??? -
ModelAdmin ManyToManyField can be empty?
I have the class Tag with ManyToManyField: class Tag(models.Model): templates = ManyToManyField(Template, related_name='tags') And TagAdmin class in admin.py from django.contrib import admin from . import models @admin.register(models.Tag) class TagAdmin(admin.ModelAdmin): ... In django-admin require select at once value for field templates. But I don't want it! How I can use admin without required field templates. -
How to make choices with the columns?
class question(models.Model): q = models.CharField(max_length=500) choice1 = models.CharField(max_length=500) choice2 = models.CharField(max_length=500) choice3 = models.CharField(max_length=500) answer = models.CharField(max_length=500, choices=[choice1, choice2, choice3]) it's giving me this error: 'choices' must be an iterable containing (actual value, human readable name) tuples. but I don't know how to fix it? Thanks -
Django ModelChoiceField, label_from_instance object iteration
The method label_from_instance from CustomModelChoiceField, iterates one object at a time, but I need the method to receive all objects at once. This is due to a freight calculation call that waits for all objects at once for the calculation. Is it possible? from django import forms from django.utils.safestring import mark_safe class CustomModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe("My Object custom label <strong>%i</strong>" % obj.id) class MyForm(forms.ModelForm): my_field = CustomModelChoiceField(label=_('The form label'), queryset=MyModel.objects.filter(), widget=forms.RadioSelect, empty_label=None) class Meta: model = MyModel -
Delete query fields from model instance
I have a SAP Business One model called OHEM in my Django project but this ERP allow the custom fields creation for each company. Actually I have an admin for one of this company and the other would like to use them but when run the code in the company "B" database I have the next warning: The name of column 'U_INT_EMPLOYEE_CODE' don't exists. (207) The company "A" have a lot of user fields and the company "B" have another user different fields for the same model and want to use the same code for both Shared model class Ohem(models.Model): empid = models.IntegerField(db_column='empID', primary_key=True) # Field name made lowercase. lastname = models.CharField(db_column='lastName', max_length=50, blank=True, null=True) # Field name made lowercase. firstname = models.CharField(db_column='firstName', max_length=50, blank=True, null=True) # Field name made lowercase. middlename = models.CharField(db_column='middleName', max_length=50, blank=True, null=True) # Field name made lowercase. sex = models.CharField(max_length=1, blank=True, null=True) jobtitle = models.CharField(db_column='jobTitle', max_length=20, blank=True, null=True) # Field name made lowercase. type = models.IntegerField(blank=True, null=True) dept = models.SmallIntegerField(blank=True, null=True) branch = models.SmallIntegerField(blank=True, null=True) # Company A fields u_int_cod_empleado = models.IntegerField(db_column='U_INT_COD_EMPLEADO', blank=True, null=True) # Field name made lowercase. u_hbt_contrasena = models.CharField(db_column='U_HBT_Contrasena', max_length=100, blank=True, null=True) # Field name made lowercase. u_hbt_cardcode = models.CharField(db_column='U_HBT_CardCode', max_length=15, blank=True, … -
Django extending the User model in ECommerce application
I have a django ecommerce project that works fine till I decided to improve it. User place order and every time they place an order they have to always input their details (name, emil, address etc) , I decided to upgrade the application so if user had registered before no need to enter details again . orders/models.py from django.db import models from django.contrib.auth.models import User from shop.models import Product from decimal import Decimal from django.core.validators import MinValueValidator,MaxValueValidator from coupons.models import Coupons class order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=50) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) coupon = models.ForeignKey(Coupons,related_name='orders',on_delete=models.CASCADE ,null=True,blank=True) discount = models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(100)]) class Meta: ordering = ('-created',) verbose_name = "order" verbose_name_plural = "orders" def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) def get_total_cost_after_discount(self): total_cost = sum(item.get_cost() for item in self.items.all()) return total_cost - total_cost * (self.discount / Decimal('100')) class OrderItem(models.Model): order = models.ForeignKey(order,related_name='items',on_delete=models.CASCADE) product = models.ForeignKey(Product,related_name='order_items',on_delete=models.CASCADE) price = models.DecimalField(max_digits=10,decimal_places=2) quantity = models.PositiveIntegerField(default=1) class Meta: verbose_name = "OrderItem" verbose_name_plural = "OrderItems" def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity I create account app and extended django user so that … -
how can i add a variable that uses a view function into signals
i am trying to add a field into my Profile creation signals, this field is the ip of the user, i have a function view that when called returns the user ip, this function needs a request argument, i want this field to be added when a user registers a new account and when this happens the signals would be called and then the profile model would be created with the ip field. signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() views.py def register(request): form = UserReg(request.POST or None) if form.is_valid(): user = form.save() login(request, user) return redirect('shop-home') form = UserReg() context = { 'form' : form, 'login': 'Log in' } return render(request, 'users/register.html', context) models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ip = models.CharField(max_length=45) -
django.core.exceptions.FieldError: Cannot resolve keyword 'redirect' into field. Choices are: added, edited, id, ip_address, name, notes
I am recieving a FieldError specifically the code not being able to resolve a keyword when attempting to run my server. I am currently upgrading my server from django 1.1 to django 2.2 and when trying to run the server the "django.core.exceptions.FieldError" is listed in the traceback telling me that the keyword "redirect" in line 326 cannot be resolved into a field. All other solutions online seem to be for a specific line of code and their resolutions have not worked in trying to resolve my issue. Here is the traceback: File "/var/www/guindev.sandiego.edu/html/Projects/usdpages/usdpages/services/urls.py", line 3, in <module> from usdpages.services.views import RedirectHostList, RedirectsFile, ImportFile File "/var/www/guindev.sandiego.edu/html/Projects/usdpages/usdpages/services/views.py", line 227, in <module> class ImportForm(forms.Form): File "/var/www/guindev.sandiego.edu/html/Projects/usdpages/usdpages/services/views.py", line 229, in ImportForm server = forms.ModelChoiceField(queryset=Host.objects.redirected(), initial=defaultHost) File "/var/www/guindev.sandiego.edu/html/Projects/usdpages/usdpages/services/models.py", line 329, in redirected return self.filter(host__isnull=False).distinct() File "/usr/local/lib64/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib64/python3.6/site-packages/django/db/models/query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib64/python3.6/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib64/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib64/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/usr/local/lib64/python3.6/site-packages/django/db/models/sql/query.py", line 1190, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/usr/local/lib64/python3.6/site-packages/django/db/models/sql/query.py", line 1049, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) … -
DJANGO - How to fix "Incomplete response received from application"
I must be going crazy... If I have my views.py file with 48 or less lines, when I POST data to it, I see Incomplete response received from application However, If I have 49 lines or more I get a NameError, 'request' is not defined thrown on line 31 and 49, even if line 31/49 is empty. Could someone please explain what is happening? Also btw Django Admin - "Incomplete response received from application" does not answer my question. veiws.py: from django.shortcuts import render from django.shortcuts import render from django.shortcuts import HttpResponse from django.core.exceptions import * from datetime import datetime def remove_xss(chat, request): return chat def find_urls(chat, request): new_chat = ' '.join([('<a href="{}">{}</a>'.format(word, word) if ('http://' in word or 'https://' in word) else word) for word in chat.split(' ')]) return new_chat def format_chat(chat, username, request): chat = remove_xss(chat, request) chat = find_urls(chat, request) request = request return "hi" def chat_index(request): return render(request, 'chatroom.html') def chat(request): if request.method == 'POST': chat = request.POST.get('textfield', None) if request.user.is_authenticated(): u = request.user.username f_chat = format_chat(chat, u, request) else: return HttpResponse('You must be signed in to continue') with open('chats.txt', 'a') as chats: chats.write(f_chat) return render(request, 'chatroom.html') urls.py: (Working (i think)) from chat import views from … -
How to modify django task in external app
I need to make some changes to a 3rd party app to enable additional functionality. This app has several tasks that make RPC calls via a service proxy that need to be updated to use a different command based on whether the associated object supports the new functionality. I've managed to update one of several of these functions but I wanted to ask the community if there was a more pythonic/DRY to do this using a decorator or pattern that I'm not thinking of. More precisely, I'm trying to add support for shielded transactions to a cryptoasset wallet while maintaining backward compatibility. I've forked the django-cc library (https://github.com/limpbrains/django-cc). I've updated the currency model to include a boolean to indicate shielded transactions are supported. Within the tasks, I've put a if statement to switch between the two. It works, but before I start refactoring the rest of the code, I want to know if there's an interface or strategy pattern I can use that would be more appropriate. We're interested in the AuthServiceProxy (https://github.com/jgarzik/python-bitcoinrpc/blob/master/bitcoinrpc/authproxy.py) object coin. The object uses a call function, so getnewaddress is passed out as as param to the RPC call. The asset we're adding doesn't support this … -
How to perfrom a aggregate query with condicional filter in django
I have this data on the model: [ {"Field": "value1", "Flag": true}, {"Field": "value2", "Flag": false}, {"Field": "value1", "Flag": true}, {"Field": "value2", "Flag": true}, {"Field": "value1", "Flag": false}, {"Field": "value2", "Flag": false}, {"Field": "value1", "Flag": false} ] I try to aggregate the data with this query when the flag is True: model.objects.values('Field').order_by('Field').annotate(total=Count('Field'), Flag=Count('Flag', filter=Q(Flag=True))) And I expect this output in the result of the query: [ {"Field": "value1", "total": 4, "Flag": 2}, {"Field": "value2", "total": 3, "Flag": 1} ] try with conditional aggregation but display this error: SQLDecodeError -
How to access its object query properties I know it have 5 properties in it
I wanna access <QuerySet [<User: xyz>]> this object properties it have multiple properties but i dont know how to access each property and update its value u = User.objects.filter(username=username) u.first_name=(str(first_name)) u.save(` -
Why is this ModelForm not valid
I'm new to coding with django, and I'm trying to add comments to my blog app, but I'm having trouble with the validation of this form, it always returns False with form.is_valid(), so the object is never saved views.py def blog_post_detail_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) comments = Comment.objects.filter(blog_post=obj) initial_data = { "blog_post": obj, } form = CommentModelForm(request.POST or None, initial=initial_data) if form.is_valid(): comment_obj = form.save(commit=False) comment_obj.user = request.user comment_obj.save() form = CommentModelForm() else: print('not clean') context = { "object": obj, "comments": comments, "form": form, } template_name = 'blog/detail.html' return render(request, template_name, context) forms.py from django import forms from .models import Comment class CommentModelForm(forms.ModelForm): class Meta: model = Comment fields = ['content','blog_post'] HTML <form method='POST' action='.'> {% csrf_token %} {{ form.as_p }} <button type='submit'>Send</button> </form> models.py class Comment(models.Model): content = models.TextField(max_length=300) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=1) blog_post = models.ForeignKey(BlogPost, null=True, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.user.username) def __str__(self): return str(self.user.username) -
how to hide in the dropdown list the required value using ajax and jquery with django
i have a dropdown list that display the data from the database. i need to make dynamic using jquery and ajax where it will hide some values based on the user input. where the user will have three options to select between and based on his selection the value will show or be hidden in the dropdown list. my question is how to hide the required option based on the returning ID. until now this what i tried and it did not work as i want. views.py def getSource(request): sources = Source.objects.all() return render(request, 'create_folder.html', {'sources':sources}) create_folder.html case"1": $('#mouresaleMasdar option[data-id="40"]').hide() and i tried another solution also didn't work. $('#mouresaleMasdar option[value="{{ source.id }}== 40"]').hide() -
Django 2.2 translations not applying, LANGUAGE_CODE and i18n URL pattern correct
I'm using Django 2.2 and Python 3.7. I'm trying to set up Django translations, and everything seems to work up until the point of seeing the translations. I'm using i18n urls so the url shows up as localhost/language-locale example: localhost/en-us/ localhost/fr-fr/ url patterns: urlpatterns += i18n_patterns( path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), path('i18n/', include('django.conf.urls.i18n')), ... settings_l10_i18.py: LANGUAGE_CODE = 'en-us' LANGUAGES = [ ('en-us', _('US English')), ('en-gb', _('British English')), ('en-ca', _('Canadian English')), ('fr-fr', _('French')), ('fr-ca', _('Canadian French')), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False USE_THOUSAND_SEPARATOR = True LOCALE_PATH = [ os.path.join(BASE_DIR, "locale"), ] file structure basedir/locale ├── en_CA │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── en_GB │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── en_US │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── fr_CA │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── fr_FR │ └── LC_MESSAGES │ ├── django.mo │ └── django.po └── README.md Language switcher in template: <li> <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"/> <select name="language" value="" onchange="this.form.submit()"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" {% …