Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When saving an object from the django admin panel, I get error 400
When I create an object in django admin when I click save, nothing happens, I get an error. Request URL: /api/admin/advertisements/advertisements/add/ Request Method: POST Status Code: 400 Bad Request Request sent to a non existent address, I didn't redefine anything, no validation happens. Everything is fine with the other models. There is nothing wrong with the venv environment. The code of this model is standard. class Advertisements(models.Model): user = models.ForeignKey(Users, verbose_name="User", null=True, blank=True, on_delete=models.CASCADE) category = models.ForeignKey(Categories, verbose_name="Category", on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategories, verbose_name="Subcategory", on_delete=models.CASCADE) name = models.CharField("Name", max_length=100) def __str__(self): return self.name class Meta: verbose_name = "advertisement" verbose_name_plural = "dvertisements" -
Django runserver error "TypeError: __init__() takes 1 positional argument but 2 were given"
I understand that somewhere 2 parameters are passed when 1 is needed only, but I can't seem to figure out where. I was in the process of updating Django from 1.9 to 1.11. Most answers relate to views, but all my views are class based and had as_view already. the exact traceback is: Traceback (most recent call last): File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mezzanine/core/management/commands/runserver.py", line 163, in inner_run super(Command, self).inner_run(*args, **kwargs) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 146, in inner_run handler = self.get_handler(*args, **options) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/mezzanine/core/management/commands/runserver.py", line 166, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 28, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in get_handler return get_internal_wsgi_application() File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/pp/www/Hakomo/hakomo/hakomo/wsgi.py", line 20, in <module> application = get_wsgi_application() File "/Users/pp/.pyenv/versions/3.7.13/lib/python3.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application return … -
How do I fix the error of my django form not having cleaned_data attribute?
I have this form class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "pass"] and this view def register(req): if req.method == 'POST': form = RegisterForm(req.POST) print('yaml') if form.is_valid(): form.save() return redirect("/home") else: form = RegisterForm() form.save() return render(req, "users/register.html", {"form":form}) but when I visit the url urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), path('register/', userViews.register, name="register"), path('', include("django.contrib.auth.urls")), ] I keep getting this error Internal Server Error: /register/ .... AttributeError: 'RegisterForm' object has no attribute 'cleaned_data' Please I need some help. Thanks in advance -
What are the parameters that Django use to generate session id
What are the parameters needed to generate a default Django sessionid I am assuming: def generate_session(secrete_keys, current_time, string_key_name, what_else?): return generate(...) -
how do i switch between two form on a page with login and sign up views in django
I have a page that has both login and sign up form in the html. so when one is active, the other is hidden but any time i try to login, the sign up form is displayed instead of the login form. the sign up tab works but the login tab does not. This is my html page: <div class="form-box"> <div class="form-tab"> <ul class="nav nav-pills nav-fill" role="tablist"> <li class="nav-item"> <a class="nav-link" id="signin-tab-2" data-toggle="tab" href="#signin-2" role="tab" aria-controls="signin-2" aria-selected="false">Sign In</a> </li> <li class="nav-item"> <a class="nav-link active" id="register-tab-2" data-toggle="tab" href="#register-2" role="tab" aria-controls="register-2" aria-selected="true">Register</a> </li> </ul> <div class="tab-content"> <div class="tab-pane fade" id="signin-2" role="tabpanel" aria-labelledby="signin-tab-2"> <form action="{% url 'estores:login' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="singin-email-2">Username or email address *</label> <input type="text" class="form-control" id="singin-email-2" name="username" required> </div><!-- End .form-group --> <div class="form-group"> <label for="singin-password-2">Password *</label> <input type="password" class="form-control" id="singin-password-2" name="password" required> </div><!-- End .form-group --> <div class="form-footer"> <button type="submit" name="login" class="btn btn-outline-primary-2"> <span>LOG IN</span> <i class="icon-long-arrow-right"></i> </button> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="signin-remember-2"> <label class="custom-control-label" for="signin-remember-2">Remember Me</label> </div><!-- End .custom-checkbox --> <a href="#" class="forgot-link">Forgot Your Password?</a> </div><!-- End .form-footer --> </form> <div class="form-choice"> <p class="text-center">or sign in with</p> <div class="row"> <div class="col-sm-6"> <a href="#" class="btn btn-login btn-g"> <i class="icon-google"></i> Login With Google … -
action after time is expired in django
I am creating auctions website using django. the user can create auctions by input this fields: title, description, image, startprice, stutasvalue and time. class Auction(models.Model): title = models.CharField(max_length=30) description = models.TextField() startprice = models.IntegerField(default=1) image = models.ImageField(upload_to="auction/") statusvalue = (("Soon", "Soon"), ("Live", "Live"), ("Expired", "Expired")) status = models.CharField(max_length=10, default="Soon", choices=statusvalue) time = models.IntegerField(default=1) def __str__(self): return self.title I can Live the auction from admin-panel. how can I convert statusvalue from Live to Expired after the time is expired? If we bear in mind that time is the number of hours in which the auction must be live. and how can I make counterdown for this time. -
'manager_method() argument after ** must be a mapping, not str' when overloading nested ModelSerialiver.create(...)
I want to overload a ModelSerializer create() method in a generic way using Django RestFramework inspection functions. for the purpose of testing the concept on a related_name of a ForeingKey i have the following models and corresponding serializer. models.py class Country(models.Model): pass class People(models.Model): country = models.ForeignKey( to="myapp.Country", null=True, blank=True, on_delete=models.SET_NULL, related_name="country_people" ) serializer.py class CountrySerializer(serializers.ModelSerializer): country_people = PeopleSerializer(many=True) def create(self, validated_data): country_people_data = validated_data.pop("country_people", []) instance = super().create(validated_data) for cp_data in country_people_data: cp_data["country"] = instance self.get_fields()["country_people"].create(cp_data) class Meta: fields= "__all__" model = Country example of data # json data for country serializer { ..., "country_people":[ {...}, {...} ] } When calling CountrySerializer.save() the CountrySerializer.create() will be called and it will save also nested data on People table. The issue is that I got the following error ModelClass._default_manager.create(**validated_data) TypeError: django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str using People.create(**cp_data) is working but it is not the solution in my context I want to solve it using self.get_fields because I want it to be generic and because PeopleSerializer could nest another serializer so back and so forth -
I want to show the total rows beside the search and make search code work in python?
I created a table and I want to do a search for two columns (id and name) so when the user enters any letter or number of name, id columns it shows all row names containing that letter and I want to show the total rows of my table next to search box. in HTML <table class="table table-striped " id="table1"> <tbody> {% for i in data_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{i.employee_code}}</td> <td>{{i.employee_name}}</td> <td>{{i.email}}</td> </tr> {% endfor %} </tbody> </table> In JS I did the search code but it does not work! function searchrecords() { var input,table,tr,td,filter; input=document.getElementById("searchtext"); filter=input.value.toUpperCase(); table=document.getElementById("table1"); tr=table.getElementsByTagName("tr"); for(i=0;i<tr.length;i++) { td=tr[i].getElementsByTagName("td")[0]; if(td) { textdata=td.innerText; if(textdata.toUpperCase().indexOf(filter)>-1) { tr[i].style.display=""; } else { tr[i].style.display="none"; } } } } -
'Media' object has no attribute 'render_styles'
I am getting this error when I try to go to the Django admin category page. my grunt.js page: module.exports = function(grunt) { grunt.initConfig({ sass: { dist: { options: { style: 'compressed' }, files: { 'static/styles/css/style.css': 'media/assets/styles/sass/style.scss' } } }, watch: { sass: { files: ['media/assets/styles/sass/*.scss'], tasks: ['sass:dist'] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['sass:dist']); }; When I try to go to the django admin, I have no problem but when try to go to the category page or user page, I got this error: AttributeError at /admin/bookmark/category/ 'Media' object has no attribute 'render_styles' Request Method: GET Request URL: http://localhost:8000/admin/bookmark/category/ Django Version: 4.0.3 Exception Type: AttributeError Exception Value: 'Media' object has no attribute 'render_styles' Exception Location: C:\Users\moust\Workspace\python_projects\saas_app\venv\lib\site-packages\django\forms\widgets.py, line 97, in <genexpr> Python Executable: C:\Users\moust\Workspace\python_projects\saas_app\venv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\moust\\Workspace\\python_projects\\saas_app', 'c:\\users\\moust\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\moust\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\moust\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\moust\\appdata\\local\\programs\\python\\python39', 'C:\\Users\\moust\\Workspace\\python_projects\\saas_app\\venv', 'C:\\Users\\moust\\Workspace\\python_projects\\saas_app\\venv\\lib\\site-packages'] Server time: Sun, 17 Apr 2022 05:14:14 +0000 this is the suit of the error message -
How can I change django form error strings [duplicate]
I use hebrew with django and when I submit a form and there's an error, the grammar of the message is not correct, how can I change form error strings? -
Why my exports are limited to 100 records only in django-import-export?
I am using Django import export in my project. I have ~5000 records in the model. In local, The export is working fine. [exporting all the records in csv] But in production, when I export to csv, Only 100 records are exported. The django app is hosted on Cpanel. I am using mysql phpmyadmin in production. Is there any limit in the cpanel to export in django import-export module which I can change because the problem I am facing in production only. database config in settings.py DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': '********', 'USER': '*********', 'PASSWORD': '*********', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'STRICT_ALL_TABLES', }, } } Model class Treatment(models.Model): clinic = models.ForeignKey(Clinic,on_delete=models.CASCADE,related_name='alltreatments', null=True) slug = models.SlugField(null= True, blank= True) language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='treatmentlanguage', blank= True, null=True) searched_treatment = models.CharField(max_length= 256, blank= False, null= False) price = models.FloatField(blank= False, null= False) price_type = models.CharField(max_length= 256, blank= True, null= True) package_info_1 = models.CharField(max_length= 556, blank= True, null= True) package_info_2 = models.CharField(max_length= 556, blank= True, null= True) package_info_3 = models.CharField(max_length= 556, blank= True, null= True) package_info_4 = models.CharField(max_length= 556, blank= True, null= True) currency=models.ForeignKey(Currency,on_delete=models.CASCADE,related_name='currency',blank=True,null=True) created= models.DateTimeField(auto_now=True) status = models.BooleanField(default= True) class Meta: # unique_together = ('clinic', 'searched_treatment', 'language') … -
Django JWT Auth for custom model
I have a custom user model class User(models.Model): fields... It also has a email, password field among other detail fields. I want to use the simplejwt JWT authorization which takes email and password as input and generates JWT Tokens. Most tutorials include creating a superuser and passing username password of the superuser to get the token, But I want to do this for my custom user model. -
Best way to implement highly customized Django admin action
I'm trying to implement a custom Admin action that creates an OwnerInvoice object based on data from Receivable and Reservation objects. All Receivable and Reservation objects are related to only one Property object. Ideal workflow: Business admin selects property X to bill and shows a list of Reservation objects which are related to property X and haven't been billed yet. Admin can select which Reservation objects should be billed and a breakdown of the Reservation data selected is shown. On the same page, the admin should be able to choose from a list of Receivable objects (all related to property X and not yet billed). After selecting Receivables, a final page shows the breakdown of Reservation and Receivable objects and provides a total. By pressing save, an OwnerInvoice object is created and a PDF (OwnerInvoice method) is generated. The question: How would the StackOverflow community recommend I implement this kind of functionality into the Django admin? Possible ideas I've had but not sure if they would work with the above flow: Extend the OwnerInvoice's application app_index admin template to show a custom table containing Property object information. Use redirects for intermediate pages (using Reservation change_list and Receivable change_list). Extend the … -
Django Serializer saves the object twice
I have a database with songs. Every song has a mainartist and all other artists are listed in an M2M as artists. I'm consuming data the API like this: def populate_song(uuid): full_endpoint = settings.API_HOST + settings.GET_SONG_BY_ID + uuid headers = { 'x-app-id': APP_ID, 'x-api-key': API_KEY, } r = requests.get(full_endpoint, headers=headers) # Create Python object from JSON string. if 'object' in r.json(): try: song = r.json()['object'] song['duplicate'] = False existingsong = Song.objects.filter(uuid=song['uuid']).first() if existingsong: data = SongSerializer(existingsong, data=song) else: data = SongSerializer(data=song) data.is_valid(raise_exception=True) return data.save() except Exception as err: print('Error saving the song with ID:' + uuid) print(Exception, err) if 'errors' in r.json(): # if Song is not found or is giving an error, mark this in the DB as duplicate. Song.objects.filter(uuid=uuid).update(duplicate=True) return This is the serializer for the song: class SongSerializer(serializers.ModelSerializer): artists = ArtistSerializer(many=True, required=False) mainartist = ArtistSerializer(many=True, required=False) def create(self, validated_data): artists_data = validated_data.pop('artists', None) # AT THIS POINT THE ERROR BREAKS THE CODE song = Song.objects.create(**validated_data) for artist_data in artists_data: artist = Artist.objects.filter(uuid=artist_data.get('uuid')).first() if not artist: artist = Artist.objects.create(**artist_data) if not song.mainartist: song.mainartist = artist # populate mainartist with the first SC artist continue song.save() continue song.artists.add(artist) return song def update(self, instance, validated_data): artists_data = validated_data.pop('artists', None) instance.artists.clear() … -
can i launch a jango app from within pycharm without using terminal?
with other projects i've developed i have been able to hit 'run' to launch my application, and then shift+f10 from then on. it seems excessively cumbersome to have to launch the terminal and type python manage.py runserver every time i want to test something... is there a better way? can i write a python file like "run.py" with some script that will launch the app, or some other solution? i've searched for ages, and all i can find is a thousand tutorials telling me how to start a project, rather than how to launch it more easily. thanks -
Auto execute background tasks in django
I am trying to automatically run background tasks as soon as the server starts in django. Specifically, after the server boots and is running on localhost, I want it to run functions that fetch api data to fill my DB. What is the best way to do this? Is it celery? Django-background-tasks is outdated for the lastest version of Django. I am trying to mess around with redis/rq and rq works when attached to a view but I still dont know how to actually have django run anything upon server load. Any guidance would be appreciated. Thank you! -
Is using something like Celery the only way to make scheduled background tasks?
Is there any alternative to Celery and other outdated libs such as django background tasks to run tasks in x seconds interval? -
I want a certain python script to be run when a Django project starts. Where should it be placed?
Also where should things be configured so that this specific script runs first. -
Instagram followersssssss
I didn’t post a fancy and word-playing title. We are all social media brothers and let’s not fool anyone: I follow who follows! Being followed is a very uncomfortable and dangerous situation. In real life. In digital life, the equation is ‘slightly’ different. Which is disturbing and dangerous; not to be followed. Unfamiliarity of followers is not an inconvenience, but a reason for happiness. We don’t get depressed anymore, we look at a friend whose name is ‘disapproval’ and go out. This is the reality of the world – the digital one – whether we like it or not. I also offer a huge service to dear readers for the needs of the day, and this week I am giving tips on how to increase your followers on Instagram. Use labels. If possible, choose those that encourage mutual following, such as #instafollow, #l4l, followback. Follow those who use these tags. Do not neglect the ‘TagForLikes’ application, which allows you to instantly use the most popular tags practically. Like random photos of different people (Don’t always heart beautiful/handsome people, mix trees/plains together. Your girlfriend sees them). In one experiment, it turned out that for every 100 random photos liked, six followers … -
How to append a list in jinja3
I am new to Django and Python. I have a nested forloop in my html template which removes an item from a list with each loop: {% for item in horizontal_list %} {% with vertical_list=vertical_list.pop %} {% endwith %} {% for item in vertical_list %} {{ form.board }} {% endfor %} {% endfor %} The idea behind it is that I am trying to create a hexboard and with the above loop I am able to achieve the following: O O O O O O O O O O O O In other words, the following peace of code is working as expected in the above example: {% with vertical_list=vertical_list.pop %} {% endwith %} However, for the top half of the board, I need a very similar loop but instead of using pop, I need to append the list: {% with vertical_list=vertical_list.append %} {% endwith %} At the moment, it does not append the list and the end result is similar to: O O O O O O <-------- this list here should be appended O O O O O O O O O O O O I am struggling to understand why pop would work in jinja but not … -
What is the best file format for exporting django postgres database
I am working on an app where the user owns a database, I would like to add a feature that allows the user to export his database into various file formats like CSV, JSON, and excel. which of these file formats are the best/easiest to export to while not losing information like metadata? tech used: Django, PostgreSQL -
Djago schedule stuck after While True
After I add this lines, following the schedule docs example, my server stucks and I cant even kill it with ctrl + C, the code is at the very bottom of my app views.py, where should I be adding this while loop command? schedule.every(30).seconds.do(getEvents) while True: schedule.run_pending() time.sleep(1) -
How to set max booking per time If I say I want to set every time an example at 8AM users can book max limit 10 times
models.py class BookingSettings(models.Model): # General booking_enable = models.BooleanField(default=True) confirmation_required = models.BooleanField(default=True) # Date disable_weekend = models.BooleanField(default=True) available_booking_months = models.IntegerField(default=1, help_text="if 2, user can only book booking for next two months.") max_booking_per_day = models.IntegerField(null=True, blank=True) # Time start_time = models.TimeField() end_time = models.TimeField() period_of_each_booking = models.CharField(max_length=3, default="30", choices=BOOKING_PERIOD, help_text="How long each booking take.") max_booking_per_time = models.IntegerField(default=1, help_text="how much booking can be book for each time.") views.py from django import forms from booking.models import BookingSettings class BookingDateForm(ChangeInputsStyle): date = forms.DateField(required=True) class BookingTimeForm(ChangeInputsStyle): time = forms.TimeField(widget=forms.HiddenInput()) class BookingCustomerForm(ChangeInputsStyle): user_name = forms.CharField(max_length=250) user_email = forms.EmailField() user_mobile = forms.CharField(required=False, max_length=10) class BookingSettingsForm(ChangeInputsStyle, forms.ModelForm): start_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) end_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) def clean(self): if "end_time" in self.cleaned_data and "start_time" in self.cleaned_data: if self.cleaned_data["end_time"] <= self.cleaned_data["start_time"]: raise forms.ValidationError( "The end time must be later than start time." ) return self.cleaned_data class Meta: model = BookingSettings fields = "__all__" exclude = [ # TODO: Add this fields to admin panel and fix the functions "max_booking_per_time", "max_booking_per_day", ] how to set maximum per day user can fill the slot and from where i need to start and how to set functions user can fill up to 10 times then the slot is locked. thank you img url https://imgur.com/0LoKSvj -
I have a bunch of files for a website and don't know how to put them together
I am running windows and working in Pycharm community edition for a website. I would like to run Docker in CE but I have seen that is not possible since it is only reserved for professional use. I have installed Docker desktop but that also doesn't work since you need to have Windows pro. I am basically stuck and don't see a way out. Does anyone have a solution. Maybe if there is an easy way rather than just doing everything manually. -
Django Model M2M Relationship to 2 other models from the same model
Here in my problem, I have a User model, in which a user (login) can be from the “Supplier” company or from “Customer” company. It is a M2M relationship for both sets of tables: User-Customer and User-Supplier. Can I link them this way: company = models.ManyToManyField(Customer, Supplier, on_delete=models.PROTECT, related_name='Users') enter image description here Thanks!!