Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin: admin.sites.register(MyModel) doesn't work
By mistake I deleted the migration files, and now my Admin does not register my Models, apparently because they were already registered and appeared correctly but now they do not appear and do not register them, and also if I try to do 'admin.sites.unregister' it indicates that it's not registered. How do I force djago to register my model again? :( Here my admin.py from django.contrib import admin from .models import Post, Category # Register your models here. admin.site.register(Post) admin.site.register(Category) -
Django 2.x drf-yasg how to create API in a custom method (like in swagger)
I am migrating my Django 1.11.7 to 2.x. One of the problems is swagger, it is now deprecated. And I have to now use drf-yasg for the API documentation and creation. Previously, in swagger in looks like this (django-rest-swagger==2.1.1) here is the old code snippet that works nicely in Django 1.11.7: in url.py: url(r'^api/v1/general/get_countries$', api.get_countries, name='get_countries'), in api.py: @api_view(['POST']) def get_countries(request): # ----- YAML below for Swagger ----- """ description: countries list parameters: - name: token type: string required: true location: form """ ...... return Response(countries_list, status=status.HTTP_200_OK) My question is how to do it in drf-yasg similarly, as I want to migrate this code and dont break anything on the mobile. probably try to do this on this latest stable releases: djangorestframework==3.10.3 drf-yasg==1.16.1 -
'PermissionError: [Errno 13] Permission denied:' when uploading to /media/
I get this error PermissionError: [Errno 13] Permission denied: '/svr/portfolio/media/projects/2019-09-11_05-13-24.png' when I try to upload an image to /media/ from the admin panel I tried sudo chmod -R 770 /svr but it makes my entire website unusable due to permissions. With sudo chmod -R 755 /svr it becomes usable again -
Django: How to load related model objects when instantiating a model
I have two related models (1-n). From the parent model, I am doing a lot of operations on the child model. For each operation I am calling: ItensOrder.objects.filter(order=self.pk) What is the best way to load the related objects ONLY ONCE, so I can avoid reaching the database every time I need the related objects. I've been trying this on the parent model: def __init__(self, *args, **kwargs): if self.pk is not None: self.itens = ItensOrder.objects.filter(order=self.pk) else: self.itens = None But this is wrong.... Anybody can help please!? -
How do I get rid of the password constraints (eg. password has to be 8 characters, password can't be too similar to username, etc.) in django
I need to get rid of the password constraints in the default django password register system so that a user doesn't need to have the password be eight characters or the password can't be too similar to the username, and be able to add my own password constraints such as a strength detector. -
Python What is the difference between calling "self.property" and creating a method that returns "self.property"?
Lets say I have a class like this: class SomeClass: some_property = 'property' def get_some_property(self): return self.some_property def some_method(self): pass What is difference (if any) between var1 and var2 in the following: def some_method(self): var1 = self.some_property var2 = self.get_some_property() For a less abstract example of this question, consider the FormMixin class in django.generic.views.edit, which looks something like this: class FormMixin(ContextMixin): """Provide a way to show and handle a form in a request.""" initial = {} form_class = None success_url = None prefix = None ... def get_form_class(self): """Return the form class to use.""" return self.form_class def get_form(self, form_class=None): """Return an instance of the form to be used in this view.""" if form_class is None: form_class = self.get_form_class() return form_class(**self.get_form_kwargs()) The method get_form_class returns the form_class property of self, but isn't this exactly the same as calling self.form_class? -
How to group results into array based on similar values, Django Model/Serializers
also: how to group model data based on same values in django also 2: Group serializer results based on value Like the others above I need a results returned in a particular way. I would like to group together results which contain a similar value for one column. As stated above I would like to take this: number | points | player_id -------+--------+---------- 1 | 45 | 1 1 | 68 | 2 2 | 79 | 3 2 | 70 | 4 and get this [ { "number": 1, "records": [ { "points": 45, "player_id": 1 }, { "points": 68, "player_id": 2 } ] }, { "number": 2, "records": [ { "points": 79, "player_id": 3 }, { "points": 70, "player_id": 4 } ] } ] -
How to trigger an event when django foreignkey is modified
I want to update fields in django admin site following the modification by the user of a given foreignkey field. I seek a way to trigger the event straight after foreignkey modification; not before/after save. I looked for the creation of a custom signal through sender/receiver. Also I tried to find a similar signal as the m2m_changed. Perhaps one of these path could be the solution. class Variety(models.Model): specific_name = models.ForeignKey(CatalogList, on_delete=models.CASCADE) def update_other_field(self): #DO SOMETHING EACH TIME specific_name IS MODIFIED Is there a way to trigger an event directly after a foreignkey is modified? -
display flash message with django formview
I have a Django Form that logs when it encounters and error. I would like to improve it by providing visual feedback to the user when the submit fails. Can I use the messages framework with FormView? if so how? # views.py class EventImport(LoginRequiredMixin, FormView): template_name = 'polls/event_import.html' form_class = EventImportForm def form_valid(self, form): form.import(self.request) return super().form_valid(form) # forms.py class EventImportForm(forms.Form): url = forms.URLField() def import(self, request): logger = logging.getLogger('django') try: ... except: trace_back = traceback.format_exc() logger.warning('Failed to import. %s', trace_back) messages.add_message(request, messages.warning, 'Failed to import. ') logger.info('Import complete') error int() argument must be a string, a bytes-like object or a number, not 'function' on messages.add_message(...) -
What is "Application startup file" option on Cpanel python application?
I'm trying to deploy my django project to my host using cpanel, but there are some new options in Create python applications tab. What should i set for the following items: "Application startup file" "Application Entry point" create application -
Django does not raise validation error username and password
Django does not raise validation errors added to forms.py for username and password. It does bring up validation errors for password based on the core password validation, but will not check if passwords are the same. This is all based on the base User model in Django. Can you help me figure out why the forms validation does not work? I get the following error is username is already in use or passwords do not match: "Form is not valid." The if statement if form.is_valid(): fails. Forms.py: class CustomUserCreationForm(forms.ModelForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': "form-control"})) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['username'] def clean_password(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def clean_username(self): username = self.cleaned_data.get('username') user_name = User.objects.filter(username=username) if user_name.exists: raise forms.ValidationError("Username already exists. Please try again.") return username def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.set_password(self.cleaned_data['password1']) if commit: user.save() return user Views.py: def payments(request): form = CustomUserCreationForm(request.POST) if form.is_valid(): password1 = form.cleaned_data['password1'] #this works to do Django core validation, but not form validation try: validate_password(password1) except ValidationError as e: form.add_error('password1', … -
Use a image from a server in Django template
Right now I'm storing the image in the static folder, but this is not working in production. View local_path = "checkimage/static/{}".format(image_file_name) download_blob(server_path, path + '/' + image_file_name, local_path) javascript let img = '<img src="/static/' + image_file_name + '/>'; Which is the correct approach to do this? They are several images and very heavy. -
Django variables are URL-encoded when deployed to Azure app service
This is the first time that I'm deploying an application to Azure app server. I'm facing an issue where my parameters are getting url encoded and it's replacing spaces with '%20' when I print it out in python function. I'm not using encodeURI() in javascript when I pass the request. Looks like this is only happens when deployed to Azure. Everything works as expected on local and on a Linux server. Do I need to update configuration to run django applications on Azure? urls.py path('person/<name>/', views.person, name="person"), I've also tried using url instead of path with regex but doesn't work either. url('person/(?P<name>[^/]+)/', views.person, name="person"), request url: 'GET' /person/John%20Doe/ views.py def dashboard(request, name):: print(name) # expected John Doe # actual John%20Doe return render(request, 'person.html', {'name': name}) person.html I'm using django template to render the name and it's show up as 'John%20Doe' instead of 'John Doe' <h3>{{ name }}</h3> web.config <?xml version="1.0" encoding="utf-8"?> <!-- Generated web.config for Microsoft Azure. Remove this comment to prevent modifications being overwritten when publishing the project. --> <configuration> <appSettings> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="D:\home\site\wwwroot" /> <add key="DJANGO_SETTINGS_MODULE" value="myapp.settings" /> <add key="WSGI_LOG" value="D:\home\LogFiles\1new1.log"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <add … -
Counting number of views article
Let's assume I've blog with articles. I'd like to count number of views my article in Django. For example: Views: 153. How can I count number of the views? def preview(request, id): article = Articles.objects.get(id=id) -
Django Template set value to select
I am building a dashboard which will have some information about users, i am trying to set value to select tag using Django but the value never get assigned here is my code my model look something like this class User(models.Model): first_name last_name reg_status i need to fill in the template with the reg_status, the reg_status can contain three option they are as mentioned below mailed register not register Here is how i am trying to render the content in the template {% for u in user %} <input type='text' value={{u.first_name}}/> <input type='text' value={{u.last_name}}/> <select value={{u.reg_status}> <option value='mailed'>mailed</option> <option value='register'>register</option> <option value='not register'>not register</option> </select> {% endfor %} The output give 'mailed' as selected for all instance even if the value is set to 'registered' or 'not registered' Thanks in advance -
How can I cache static pages in django bit still roll out updates?
I have designed a website in such a way that I serve exclusively static pages. What that means is that the same url always results in the exact same response, independant of user, device, browser etc, except if there was an update to the page layout. Every bit of varying data is loaded in through ajax. The idea is that after the first time the browser should only have to load the raw json data from the server, to reduce traffic, with images being hosted externally. I know djabgo has cache control that can tell the browser to hold on indefinetly, but that also means the browser will miss updates. So whats the best strategy to leverage browser cache while still serving updates? -
how to update django an object which created with formset in class based view
i want to update an object which created with formset(multi forms) in one go views.py class ProductUpdateView(LoginRequiredMixin , UpdateView): model = Order form_class = ProductOrderFormSet template_name = 'update.html' def form_valid(self , form): return super().form_valid(form) forms.py class ProductOrderForm(forms.ModelForm): product = forms.ModelChoiceField(queryset=Product.objects.filter(active=True),empty_label='') class Meta: model = ProductOrder fields = ['product','quantity'] class RequiredFormSet(BaseFormSet): def __init__(self,*args,**kwargs): super(RequiredFormSet , self).__init__(*args,**kwargs) for form in self.forms: form.empty_permitted = False ProductOrderFormSet = inlineformset_factory(Product , ProductOrder, form=ProductOrderForm,formset=RequiredFormSet , extra=1) thanks for advice -
no such table: main.auth_user__old in django
i am getting no such table :main.auth_user_old as a operational error.i am using latest django version till date(12.09.2019).and sqlite as db an pycharm as IDE.i tried all the answers which is already been given for the same no such table error.but nothing worked for me.i could not able to add user or groups or products.i am facing this operational error .please help me to resolve this issue.Thanks in advance -
How to install mysql in my Django project using pip or any other tool in python 3.7
I've build a django project using python 3.7, Now I'm trying to deploy my project on Google App engine, and trying to use mysql locally for testing. After going through multiple question/answers/documentation still I'm unable to install mysql correctly. I tried following options: 1. pip install mysqlclient 2. brew install mysql-connector-c 3. pip3 install http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.0.4.zip 4. pip install mysql-connect-python 5. pip install pymysql But none of the above is working for me. -
In django user model what does @propery represents
Below is the code from sample custom user model with staff field. I am new to Django framework. Can anyone explain what is the difference between @propery and without specifying it? It's not making sense with or without it in terms of accessing it. Does @propery provides any additional functionality like setting the fields values. Correct me if I am wrong @property def is_staff(self): "Is the user a member of staff?" return self.staff def is_staff(self): "Is the user a member of staff?" return self.staff -
Django - Migrating SQLite to Postgre DB on Remote(Heroku)
My Django, SQLlite website is up and running remotely, thanks to all the help here. Now I wanted to migrate my data as well, I have tried several options provided in this forum, however, I have not been able to migrate the data yet Steps given in the following link has been able to fix my all issues, (none of the other options were able to help me completely) What's the best way to migrate a Django DB from SQLite to MySQL? However, the remote website is still not showing any data. ============================================================= HP@HP-PC MINGW64 ~/git_projects/django_local_library (master) $ python manage.py migrate --run-syncdb Operations to perform: Synchronize unmigrated apps: messages Apply all migrations: admin, auth, catalog, contenttypes, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. HP@HP-PC MINGW64 ~/git_projects/django_local_library (master) $ python manage.py shell Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() (56, {'auth.Group_permissions': 0, 'auth.User_user_permissions': 0, 'auth.Permission': 45, 'contenttypes.ContentType': 11}) quit() HP@HP-PC MINGW64 ~/git_projects/django_local_library (master) $ python manage.py loaddata datadump.json Installed 232 object(s) from 1 fixture(s) ============================================================= After above steps, (with some, … -
Using Django channels with existing websockets
I have already a websocket server that is runnning now (that I can't modify). Every time I receive a message, I want to push it to a Django channel. Is it possible to use Django channels with an existing websocket ? -
How to render a CheckboxSelectMultiple form using forms.ModeForm that uses data from DB as SomeOtherModel.objects.filter(user=request.user)
Please take a look at the code and if you can not comprehend what is going on, I am explaining it in the end I have a model named Good class Good(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) and a form class GoodForm(forms.ModelForm): def __init__(self, request=None, *args, **kwargs): super(GoodForm, self).__init__(*args, **kwargs) self.input_list = request.user.love_set.all() self.fields['ans'] = forms.MultipleChoiceField( label="", choices=[(c.ans, c.ans) for c in self.input_list], widget=forms.CheckboxSelectMultiple ) class Meta: model = Good fields = ('ans',) and the view for this is @login_required def good_form(request): form = GoodForm(request) if request.method == 'POST': form = GoodForm(request, request.POST) if form.is_valid(): answer = form.save(commit=False) #problem is here answer.user = request.user answer.save() return redirect('app-2:money') else: form = GoodForm(request) return render(request, 'purpose_using_DB/good_at_form.html', {'form': form, 'error': 'Error occured'}) else: return render(request, 'purpose_using_DB/good_at_form.html', {'form': form}) THis code is showing me the form but an error is thrown at answer=form.save(commit=False) saying no such table: purpose_using_DB_good #purpose_using_DB is my app answer <Good: Good object (None)> So what I want to do here is :- I want to render a form called GoodForm which is a ModelForm related to the model Good. The form is rendered as the options presented already in the table called Love. query Love.objects.filter(user=user) is equivalent to … -
Migrating from CharField to PostgreSQL ArrayField-of-CharField
I have a Django model with a CharField. I'd like to migrate it to a PostgreSQL ArrayField containing CharField elements. It looks like RunPython should be involved here, but how specifically should I do this? Original model: from django.db import models class TestModel(models.Model): test_field = models.CharField( max_length=128, choices=[("a", "AAA"), ("b", "BBB")], blank=True, default="", ) The database table has some rows created from this model: from my_app.models import TestModel t1 = TestModel.objects.create() # test_field == '' t2 = TestModel.objects.create(test_field="a") Now I'd like to migrate to: from django.contrib.postgres.fields import ArrayField class TestModel(models.Model): test_field = ArrayField( models.CharField(max_length=128, choices=[("a", "AAA"), ("b", "BBB")]), default=list, blank=True ) ...with any case where test_field is, in the original model, the empty string "", becoming the empty list in the new model & DB field, []. In Python-space this would look like: convert_ftype = lambda val: [val] if val else [] So that the two model instances from above become: t1 = TestModel.objects.create() # test_field == [] t2 = TestModel.objects.create(test_field=["a"]) Running simply ./manage makemigrations && ./manage migrate throws a django.db.utils.DataError, which is not surprising. -
Table 'auth_user' already exits , when I try to migrate new tables to my local mysql database
I am trying to deploy a django project on my local machine. I am new to django as well as python. As far as I know, when I run migrate, my_app tables along with django's table should be visible in my local database. I run makemigration app_name command and can see the correct SQL query is generated for my table. However, when I run migrate command, I get the " table 'auth_user' already exists" error. My database is already empty before I run this. Also my migration folder has just the init.py file only Error Log: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, impact_mapping, sessions Running migrations: Applying impact_mapping.0001_initial...Traceback (most recent call last): File "C:\Users\dpanch378\CBAT\component_mapping\env\lib\site-packages\django\db\backends\utils.py", line 62, in execute return self.cursor.execute(sql) File "C:\Users\dpanch378\CBAT\component_mapping\env\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "C:\Users\dpanch378\CBAT\component_mapping\env\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "C:\Users\dpanch378\CBAT\component_mapping\env\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "C:\Users\dpanch378\CBAT\component_mapping\env\lib\site-packages\MySQLdb\connections.py", line 226, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1050, "Table 'auth_user' already exists") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\dpanch378\CBAT\component_mapping\env\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\dpanch378\CBAT\component_mapping\env\lib\site-packages\django\core\management__init__.py", line 356, in …