Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the difference between save() and clean() method in django? Who is the first to be called when instantiating a model? [closed]
I want to make a blog in Django I have an Article table and a Blogger table I would like the number of blogger articles to be incremented with each record. However, it should not be incremented if it is an update. I tried to overload the clean() method but with each update the number of blogger articles also increases. I tell myself that if I understand how these two work I would know how to use them better that'is what i have tried from django.utils.text import slugify from django.conf import settings from django.db import models import uuid import datetime from django.shortcuts import reverse from user_cust.models import Blogger class Articles(models.Model): """Attributes list of my articles""" blogger = models.ForeignKey( Blogger, on_delete=models.CASCADE, primary_key=False, default="", verbose_name="Auteur:", editable=True, ) id = models.UUIDField( unique=True, primary_key=True, default=uuid.uuid4, ) title = models.CharField(max_length=200, verbose_name="Titre") slug = models.SlugField(default="", max_length=200, blank=True) body = models.TextField(blank=False, null=False, default="") created_at = models.DateTimeField(auto_now_add=True, verbose_name="Cree le:") update_at = models.DateTimeField(auto_now=True, verbose_name="Mis a jour le: ") image = models.ImageField(upload_to="article_images", blank=True) def __str__(self): return f"{self.title}" def save(self, *args, **kwargs): value = self.title self.slug = slugify(value=value, allow_unicode=True) if self.blogger.nb_articles == 0: self.blogger.nb_articles += 1 self.blogger.save() super().save(*args, **kwargs) def clean(self): """Try to avoid that an update action add a number … -
import all sections of the connected user's profile on LinkedIn using the LinkedIn API
I want to import all sections of the connected user's profile on LinkedIn using the LinkedIn API in Python. I used the REST API to retrieve profile information by sending a GET request to the URL: https://api.linkedin.com/v2/me, using the obtained access_token. However, I want to import the education and experience sections, and I am unsure of what to add to the URL to achieve this. What parameters do I need to add to the URL to retrieve the education and experience sections of the connected user's profile using the LinkedIn API in Python?" i tried this url " api_url = 'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,headline,profilePicture(displayImage~:playableStreams),educations,experience)' " but when i execute this url form : response = oauth.get(api_url) profile_data = response.json() the profile_data contain only the name , image profil and emailAdress . -
how we can connect two table in django model
**I am new to django i am working on a project where I have 4 usertype 1- super admin 2- sub admin 3 - clinic 4 - patient Now I want to make the login for all the 4 usertype** right now I have create a model like this import django from django.db import models from django.contrib.auth.models import AbstractUser class Registered_user(AbstractUser): is_clinic = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) token = models.CharField(max_length=120, default=None, null= True) forgot_token = models.CharField(default=None, max_length=120, null=True), email = models.EmailField(unique = True, max_length=254, verbose_name='email address') updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(default=django.utils.timezone.now) #clinic clnc_name = models.CharField(max_length=255) clnc_phone = models.BigIntegerField(null= True) clnc_contact_name = models.CharField(max_length=255) clnc_Job_Title = models.CharField(max_length=255) clnc_address_line1 = models.CharField(max_length=255) clnc_address_line2 = models.CharField(max_length=255) clnc_county = models.CharField(max_length=255) clnc_postcode = models.CharField(max_length=255) clnc_town_city = models.CharField(max_length=255) clnc_created_at = models.DateTimeField(auto_now_add=True) clnc_status = models.BooleanField(default=False) #Patient punique_number = models.CharField(max_length=20) pname= models.CharField(max_length=255) patient_adddress = models.TextField(max_length=500) pphone_number = models.IntegerField(null=True) phome_number = models.IntegerField(null=True) pwork_number = models.IntegerField(null=True) pdob = models.CharField(max_length=255,null=True) relative_name = models.CharField(max_length=255,null=True) relative_phone = models.CharField(max_length=255,null=True) relation = models.CharField(max_length=255,null=True) pgender = models.CharField(max_length=20) pcreated_at = models.DateTimeField(auto_now_add=True) ptnt_status = models.BooleanField(default=False) **I want them to be seperated I know this is not the right way to do this I also tried to use the foreign key but i got null value error Please let me … -
dj-rest-auth/registration return http 204 no content
I were following the book Django for APIs by William.S.Vincent. In Chapter 8: User Authentication, I make Implementing token authentication and use dj-rest-auth and django-allauth to make registration. In the book after register the http return 201 created, it created new account and return API auth key token, save that in db. With my it return http 204 no content( not return API auth key token ), it still created a new account but don't create key token for account. My url.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include("posts.urls")), # v1 for api version 1. (Name for each api route) path('api-auth/', include('rest_framework.urls')), # build-in log in/out rest path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")), #url for dj_rest_auth path("api/v1/dj-rest-auth/registration/", include("dj_rest_auth.registration.urls")), ] My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #3party "rest_framework", "corsheaders", "rest_framework.authtoken", "allauth", "allauth.account", "allauth.socialaccount", "dj_rest_auth", "dj_rest_auth.registration", #local 'accounts.apps.AccountsConfig', 'posts.apps.PostsConfig',] REST_FRAMEWORK = { # new "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ],} I compared with github files both author and found no difference. github:https://github.com/wsvincent/restapiswithdjango/tree/master/ch8-blog-user-auth Has there been any change to the version? Thank for you time. -
WeasyPrint server error 500 on render.com
im having a 'server error 500' in my project when i tried to use Weasyprint (im not having any error when i use local host), I deploy my project on render.com it's a django app with postrgres. here is the code: html_template = get_template('printinfo.html') html_string = html_template.render({'person': passanger}) html_string = html_template.render(context) pdf_file = HTML(string=html_string).write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = f'filename="{passanger.passanger.name} Reservation.pdf"' return response Im thinking its an enviroment error but i installed my requirements.txt in render.com which has weasyprint on it. I tried to find a way to install gtk or pango in render.com but i couldnt find the way... -
Django not identifying User custom model
Error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed settings.py INSTALLED_APPS = [ ... 'apps.users', ... ] AUTH_USER_MODEL='users.User' Resolver o erro. Sem mudar o nome do app no INSTALLED_APPS -
How to annotate a Django queryset with a boolean value for "is older than n days"?
Given the toy example of a model: class Article(models.Model): title = models.CharField(max_length=64) published = models.DateTimeField() How might you get a queryset such that you can tell whether the article was published over 2 years ago? I was thinking something like this, but it didn't pan out: Article.objects.all().annotate( is_relevant=ExpressionWrapper( timezone.now() - F("start") > timedelta(days=365 * 2), output_field=BooleanField(), ) ) Basically, I want to be able to iterate over the list of articles and access article.is_relevant in the template to decide how I might render it. -
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