Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save another user in your contacts django-rest-framework
I have model of IndividualUser which has OneToOneField to user like its his profile I'm looking for way to save another user in this model like contacts in your mobile phone Or maybe i shouldnt save contacts in model but so where i can save that info? I want to do this with django-rest-framework and i'm wondering how can i do that? I think we can use m2m field there but i dont think that this is good practice for that models.py class IndividualUser(models.Model): individual_user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(_("first name"), max_length=150) last_name = models.CharField(_("last name"), max_length=150) -
Is there a way to publish a page in the past in Wagtail CMS?
In Wagtail CMS you can publish pages and even set schedules. It seems that you can't publish pages in the past. When I set a schedule in the past (e.g. 01/01/2022) and publish the page, I don't get the expected behaviour. When now accessing the pages property (first_published_at & last_published_at), I don't get 01/01/2022, but the date and time I published the date. Is there a way to achieve that? -
Disable one input in a dynamically generated <tr> with two inputs, one of them a dropdown
I have a recipe app in DJango with an inline-formset-factory. I use this to dynamically add ingredients to my recipe. The ingredient table has three inputs: A rum, an item and an amount. I now want to disable either rum or item depending on which one has a value enterd. If rum has a value, items should be disabled an the other way around. How can I get this done? I've been experimenting with an each loop but I really struggle get get anything useful out of it. Any help and pointers on learning to get better with jquery loops for things like this would be much appreciated. See my HTML code below: <tbody id="item-ingredients"> <!-- id="item-inlineformsetname" --> <!-- formset non forms errors --> <tr id="ingredients-0" class="hide_all"> <!-- id="inlineformsetname-counter" --> <input type="hidden" name="ingredients-0-id" id="id_ingredients-0-id"> <td> <select name="ingredients-0-ingredient_rhum" class="rhum ingredient-input" id="id_ingredients-0-ingredient_rhum"> <option value="" selected="">---------</option> <option value="1">Original - 50.0</option> <option value="2">Se Mettre Au Vert - 44.0</option> <option value="5">Se Mettre Au Vert - 68.0</option> </select> </td> <td> <input type="text" name="ingredients-0-ingredient_name" class="items ingredient-input" maxlength="255" id="id_ingredients-0-ingredient_name"> </td> <td> <input type="number" name="ingredients-0-ingredient_amount" step="0.1" id="id_ingredients-0-ingredient_amount"> </td> <td> <input type="checkbox" name="ingredients-0-DELETE" id="id_ingredients-0-DELETE"> </td> </tr> </tbody> -
Problem with file uploader on Django after deploy
I have a site with file uploader developed on django. But after deployment when I upload a file from one device, the same file becomes visible to all other devices on which the site is opened. But I need each user can upload his file and work with it independently. For example, on this site https://pixmiller.com/en/remove-background/ if I upload pictures from different devices, they will not interfere with each other. And I would like that my site works in this way. How can this problem be solved? Thank for any ideas. For your information: for deployment I have used Docker and Google Cloud. I don't want to create authentication system at this stage. -
How to integrate a Next.js frontend into an existing Django/Vue.js app?
I have an existing Django/Vue.js app, and the Vue.js app is using a hash character (#) before the actual URL (via vue-router). I'm planning to develop a new frontend using Next.js. Is it possible to integrate the Next.js frontend into the existing Django/Vue.js app? I would like to allow users to try out the new frontend while the existing one still works. I assume that Next.js will use v2 in the URLs. Example: https://myapp.ltd/#/profile -> Vue.js https://myapp.ltd/v2/profile -> Next.js Does anyone have any suggestions for how to approach this situation? -
Log format not recognized
I'm using pycharm on windows when i was using that on Linux everything was fine I'm parsing info from my loggers into my model db but for some reason i guess bcs log format for somehow not recognized in pycharm i got this in my model Персональный компьютер UTF-8 in my log files works good I mean i have russian letters and thats what i need but when i parse them with this: with open('loggers/log_user_activity/user_activity.log', 'r') as filelog: for i_line in filelog.readlines(): if i_line.startswith('INFO') and len(i_line.split()) == 9: I got this in console: INFO 2023-04-24 16:20:19,672 k.nefedov 127.0.0.1 Персональный_компьютер Зашёл_на_сайт - - Log settings in pycharm: -
How to store encode file data into database with django ORM which has TextField
i have a java api which store byets stream as encoded data but i don't find anything in django to do that here is Java code :` File f1=new File(publicKeyFile); File f2=new File(privateKeyFile); if(f1!=null || f2!=null) { keys=new Keys(); keys.setPublicKeyFile(f1); keys.setPrivateKeyFile(f2); } and here is how it store like that in db ÂÊLñ¢êl¹ jóEyº_ÿäFþ2ß[o‡V?óI©è4ÔågôJþ¨{A Ae`§GŽjÿ&ømnÏ' Šž‘Üè÷g¥åÿ |ß-멃¨Æ%°m”(åè}þY[S but i can't save this as in django. basically i want something like that which java code is doing please help -
Configuration for Celery during deployment
I am trying to deploy a django app on railway where I am using celery for sending email and redis as celery_broker but When I deploy it then celery don't send emails. I also use Redis Cloud and use the url of it as celery_broker_url. I want to know how to run celery on Redis Cloud. I want to send emails and it doesn't not happen -
How to add a a slug to the URL for the Django admin change page?
I want the url to the admin change pages of single objects to be /admin/app/object/object_pk/slug/change/ instead of /admin/app/object/object_pk/change/. I'd like to avoid writing custom views since in my case the built-in admin interface is used as the frontend for the app. Some users will receive only the link to a change page for read-only purposes and I'd like to increase security by adding the slug to the url. Is this in any way possible or is the Django admin not suitable for such a case? Could I alternatively write a custom view that uses the admin change form as a template? How would I be able to access the built-in template for the custom view? I already tried subclassing ChangeList to change the url_for_result: class ReportAdmin(admin.ModelAdmin): def get_changelist(self, request, **kwargs): class ReportChangeList(ChangeList): def url_for_result(self, obj): return reverse('app_report_change', args=[obj.pk, obj.slug]) return ReportChangeList This made the links for the results on the change list page disappear completely. Maybe I'm missing how to hook in the url at a different place? -
error: "fromisoformat: argument must be str"
I'm doing a website where you can be redirected from another user's profile to a page where you can send him a message by passing the argument 'username'. I managed to do most of it but when I try to send a message it shows me this error fromisoformat: argument must be str My code: views.py def user_profile(request, user_username): profile = User.objects.get(pk=int(user_username.replace("-", "").replace(" ", ""))) return render(request, 'user_profile.html', {'profile': profile}) ... def send_message(request, recipient_username): recipient = User.objects.get(username=recipient_username) if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.sender = request.user message.recipient = recipient message.save() return redirect('user_profile', recipient_username) else: form = MessageForm() return render(request, 'send_message.html', {'form': form, 'recipient': recipient}) forms.py: class Meta: model = Message fields = ['receiver', 'subject', 'body'] models.py: class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') subject = models.CharField(max_length=100) body = models.TextField() image = models.ImageField(upload_to='', blank=True, null=True) date = models.DateTimeField(default=True) is_read = models.BooleanField(default=False) message = models.TextField() def __str__(self): return self.subject I'll add more code if needed. I tried few methods that I found here but every time it shows me this or some other error. -
Django model based on queryset rather than table
I have a model called Event and a viewset called UserEventViewSet that defines the following method: def get_queryset(self): return ( Event.objects.select_related( 'user', ).values( 'user_id', 'type' ).annotate( count=Count("*"), user=JSONObject( id=F("event__user__id"), first_name=F("event__user__first_name"), last_name=F("event__user__last_name"), ), ) ) This works but it seems less than ideal. As you can see here we are doing the work of the serializer in the viewset. I think it might be better to move part of this queryset into a manager and attach it to a UserEvent model. Then I would hope I could define relations in the model and use a nested serializer for the user data. I'm not sure how to do it, or if it is even possible. -
unable to proceed further due to the error of 'update mysql client'
enter image description here Can someone please explain what exactly is this error and what should i do? Because i have tried updating mysql on my laptop to get rid of the error but it still says the same updated mysql, still no change -
Not getting token in localstorage
I am trying to get tocken from localstorage. But getting error. It showing the error like 401 unauthorized. I have mentioned auth.service.ts code. it is made to handle user login and logout service. And second one is account.service.ts to handle user registration part. Here is my code: auth.service.ts import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Observable} from 'rxjs'; import { tap } from 'rxjs/operators'; import { apiHost } from '../aoi-host-url'; import { loginModel } from './login/login.model'; @Injectable({ providedIn: 'root' }) export class AuthService { static loginUrl: string = apiHost+'users/mylogin/'; redirectUrl: string = "/dashboard"; private httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}) }; constructor(private http: HttpClient, private router: Router) { } login(data: loginModel): Observable<object> { /* This function makes the post call to API endpoint to login the user * with collected data from html form. The tap function sets the redirectUrl * to '/dashboard' */ return this.http.post<object>(AuthService.loginUrl, data, this.httpOptions).pipe( tap( _ => { this.redirectUrl="/dashboard" }) ); } logout() { /* * On logging out we need to clear the localStorage and * redirect to login page. */ localStorage.clear(); this.router.navigate(['/login']); location.reload(); } getToken(): string { const … -
i am unable to publish new app to my console the button for "accept the play app signing terms of service" is disabled. Tell me what should I do
enter image description here I was trying to publish app to my console which already has two apps live since some months but i cannot publish it because the button for accept the play app signing terms of service button was disabled. I don't know why this happened please give me solution -
Not connecting Android application to Paycharm
I wrote an API with django and my API program works fine. When I use the retrofit library to receive information from the API running by Pycharm, I encounter an error "Failed to connect to /127.0.0.1:8000","Could not remove dir '/data/data/com.example.project_____uploadfile2/code_cache/.ll/': No such file or directory". API interface public interface Api { String URL1="http://127.0.0.1:8000/api/"; @GET("get-data") Call<List<models>> getname(); } MainActivity public class MainActivity extends AppCompatActivity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView =findViewById(R.id.listview); getname1(); } private void getname1() { Call<List<models>>call=retrofitClient.getInstance().getApi().getname(); call.enqueue(new Callback<List<models>>() { @Override public void onResponse(Call<List<models>> call, Response<List<models>> response) { List<models> modelsList =response.body(); String[] name1=new String[modelsList.size()]; for (int i=0;i<modelsList.size();i++){ name1[i]=modelsList.get(i).getName(); } listView.setAdapter(new ArrayAdapter<String>( getApplicationContext(), androidx.appcompat.R.layout.support_simple_spinner_dropdown_item ,name1)); } @Override public void onFailure(Call<List<models>> call, Throwable t) { Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show(); Log.e("erorr", t.getMessage() ); } }); } } retrofitClient public class retrofitClient { private static retrofitClient Instance=null; private Api api; private retrofitClient(){ Retrofit retrofit=new Retrofit.Builder().baseUrl(URL1) .addConverterFactory(GsonConverterFactory.create()) .build(); api =retrofit.create(Api.class); } public static synchronized retrofitClient getInstance(){ if (Instance==null){ Instance=new retrofitClient(); } return Instance; } public Api getApi(){ return api; } } models public class models { public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; } I read on a … -
Anyone please help me to fix this error in Django?
I use Django for web development. When i make some changes in models then i run "Python manage.py makemigrations" and "python manage.py migrate". But at migrate code running i got some errors as follows: python manage.py makemigrations No changes detected python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, home, sessions Running migrations: Applying home.0020_image_desc_image_propertytype...Traceback (most recent call last): File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 90, in _execute return self.cursor.execute(sql, params) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__home_image.desc The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\genio\OneDrive\Documents\HamroKothaProject\hello\manage.py", line 22, in main() File "C:\Users\genio\OneDrive\Documents\HamroKothaProject\hello\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 135, in migrate state = self._migrate_all_forwards( File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\migration.py", line 130, in … -
How to create custom Django URL filter
I have set up a django project and i use the viewsets.ModelViewSet. I need to use some custom filters from my react project through url that calls to the api, something like .../model/username="Test"/ where the username is the foreignKey in my model. I deploy my backend in Heroku. Thank you I tried using different kind of ready packages, but they did not work. -
Custom User Model [closed]
I need to have a custom model for my project rather using Django's default one i need go with my own. And also i need to use Django authentication. There's an another problem when wrote a sign out view without using logout function instead i used session. fush but when press browser's back button I'm able to view the previous page is there's any alternate way to solve this??? Imma beginner at this. So basically they're saying use abstraction Base class -
backend.quote_name not working, suggest somthing to make this work
` def dump_model(model): from django.db import connection, backend opts = model._meta cursor = connection.cursor() fields, default = get_model_stru(model) cursor.execute('select %s from %s' % (','.join(map(backend.quote_name, fields)), backend.quote_name(opts.db_table))) return call_cursor(opts.db_table, fields, cursor) ` Django version I am using is 1.6.7,I tried connection.ops.quote_name, str(), also tried defining quote_name nothing seems to working -
Django Form, how to get further model info for ModelChoiceField
I have 3 models that are related to eachother. A showing has the 'film' and 'screen' foreignkeys that link to Film and Screen. I'm trying to setup a webpage so that you can view information on a showing that is already setup, and edit it from dropdowns of what films and screens are available. The problem I have at the moment is that instead of showing the screen numbers, and film titles that can be selected from, my dropdowns are showing 'Screen Object (4)' or 'Film Object (2)'. How do I get that next level of information to show from each object? My models are: class Film(models.Model): ageRatings =[ ("U", "U"), ("PG", "PG"), ("12", "12"), ("15", "15"), ("18", "18"), ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) length = models.DurationField() rating = models.CharField(max_length=3, choices=ageRatings, default="U") genre = models.CharField(max_length=50) poster_url = models.CharField(max_length=255, default='') class Screen(models.Model): id = models.AutoField(primary_key=True) cinema = models.ForeignKey(Cinema, on_delete=models.CASCADE, related_name='screens') screen_number = models.PositiveSmallIntegerField() seating_capacity = models.PositiveIntegerField() class Showing(models.Model): id = models.AutoField(primary_key=True) film = models.ForeignKey(Film, on_delete=models.CASCADE, related_name='showings') screen = models.ForeignKey(Screen, on_delete=models.CASCADE, related_name='showings') start_time = models.DateTimeField() end_time = models.DateTimeField(null=True) available_seats = models.IntegerField() adult_price = models.FloatField() student_price = models.FloatField() child_price = models.FloatField() def save(self, *args, **kwargs): self.end_time = self.start_time + self.film.length super().save(*args, … -
django.db.utils.IntegrityError: UNIQUE constraint failed: profiles_api_userprofile.id
I have created a custom model on django to create users and superuser, and now when i try to create a superuser, i get the following error django.db.utils.IntegrityError: UNIQUE constraint failed: profiles_api_userprofile.id models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError("Users must have an email address") email = self.normalize_email(email) user = self.model( email=email, name=name ) # creates a new model that the manager is representing user.set_password(password) user.save(self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with given details""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(self._db) return user # is_superuser is automatically created by PermissionsMixin class UserProfile(AbstractBaseUser, PermissionsMixin): """Database model for users in the system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name"] def get_full_name(self): """Retrieve full name of user""" return self.name def get_short_name(self): """Retrieve short name of user""" return self.name def __str__(self): """Return string representation of our user""" return self.email I added the model in the settings.py … -
Django: python manage.py runserver exits with ‘Performing system checks, what is the possible issue?
I am working on a django project and have been using python manage.py runserver to spin up my development local server, but it just started exiting at Performing system checks. This is the first time i am encountering such issue, have any one experienced this issue before, please how do i go about it? C:\Users\Destiny Franks\Desktop\ecommerce_prj>python manage.py runserver Watching for file changes with StatReloader Performing system checks... C:\Users\pc-name\Desktop\ecommerce_prj>python manage.py runserver Watching for file changes with StatReloader Performing system checks... C:\Users\pc-name\Desktop\ecommerce_prj> This is how everything looks, it does not show any error message or issue, just breaks off and return to the cmd -
Check if a code exists in Django Database
I'am trying to check if a value exists in one of my database fields so this is my models.py class Student(models.Model): username = models.CharField(max_length=200, null=True, blank=True, verbose_name='نام کاربری') code = models.CharField(max_length=10, null=True, validators=[MinLengthValidator(10)], blank=True, verbose_name='کد ملی') def __str__(self) -> str: super(Student, self).__str__() return self.username class Meta: verbose_name = 'دانش آموز' verbose_name_plural = 'دانش آموزان' I can create a model in django's panel but the thing that I want, is Checking if a property of this class exists this is my views.py class LoginView(View): def get(self: Self, request: HttpRequest) -> HttpResponse: login_form: LoginForm = LoginForm() return render( request=request, template_name='index.html', context={ 'login_form': login_form, } ) def post(self: Self, request: HttpRequest) -> Union[HttpResponseRedirect, HttpResponsePermanentRedirect, None]: login_form: LoginForm = LoginForm(request.POST or None) if (login_form.is_valid()): username = login_form.cleaned_data.get('username') code = login_form.cleaned_data.get('code') # I want to check if " code " is in database # if it exists, login # else show an error I want to check if the code variable value, exists in my database and if it exists, login else show an error I expect my code check the value existance but I don't know how to do that -
Using ForeignKey key Django to reference the 'id' from another table
I want to use the user_id as a foreign key in CPA table here is my model ---models.py---- and on the Django admin admin page It show all of the user data. **Please note that the person detail on the image have been generated using Faker. I have try using this user_id = models.ForeignKey(User,to_field='id', on_delete=models.CASCADE, default=1) I want it to show just the id number which is 1 as follow expected value How can I do that?? Thank you for your reply -
Django's bulk_create doubts
I'm adding this function to my Django app, but I have a couple of questions I need to know and which I couldn't find in Google. Does it insert all records in the order the list is given? Or can they be suffle? Can I know which id corresponds to the index in the list of the items to give? In case an error happened will it prompt which one failed, and will continue inserting the others, or will it stop inserting the rest of elements?