Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found by django urls
This my django urls path('count/(?P<pk>[0-9]+)', CountlListView.as_view()), This my my view class CountlListView(ListAPIView): serializer_class = CountSerializers def get_queryset(self,*args,**kwargs): queryset=Count.objects.all() userId=self.request.query_params.get('id') print(userId) return queryset.filter(userId=userId) and this is my models class Count(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) channelId = models.ForeignKey(News_Channel,on_delete=models.CASCADE) rate = models.PositiveIntegerField(default=0) I want to filter content based on user Id but with my code, I am getting a page not found. Please help me to figure out to filter data by user id. -
Connection refused Django requests-module
i'm trying to send GET request from my Django app to Spring app hosted in my local machine. I've tested sending requests to another websites outside localhost and it works perfectly. Problem appears when it comes to sending to http://localhost:port. This is function which is sending requests in my Django app. It works for url1 but doesnt for url2. def send_mail(request): url1 = "https://httpbin.org/get" url2 = "http://localhost:5000" response = requests.get(url2) return HttpResponse(response) Here's an error that shows wherever i try send request to localhost. HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused')) -
404 Page Not Found "GET /accounts/login/?next=/profile/ HTTP/1.1" 404
I am getting some issues with my urls. I don't have any 'account/' route but i when I want to visit 'login/' and after logging in it should redirect me to my profile... but it is taking me to this route: "http://127.0.0.1:8000/accounts/login/?next=/profile/" I am sorry if I've posted any unnecessary kinds of stuff: mainapp.urls from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from forms.views import RegisterView,LoginView from django.conf import settings from django.conf.urls.static import static from user_profile import views as profile_views from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('register/',RegisterView.as_view(), name='register'), path('login/', LoginView.as_view(), name = 'login'), path('profile/',profile_views.profile,name='profile'), path('updateprofile/',profile_views.updateprofile,name='update_profile'), path('',include('blog.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) forms.views(Login/Logout)View from django.shortcuts import render, redirect,reverse from django.http import HttpResponse from django.contrib.auth import authenticate, get_user_model, logout from django.utils.http import is_safe_url from django.contrib.auth.decorators import login_required from django.views.generic import CreateView, FormView from .models import User from .forms import RegisterForm,LoginForm class LoginView(FormView): form_class = LoginForm #instance template_name = 'forms/login.html' success_url = '/profile/' def User_logout(request): if request.method == "POST": logout(request) return redirect(reverse('login')) LoginForm: class LoginForm(forms.Form): email = forms.EmailField(label='email') password = forms.CharField(widget=forms.PasswordInput) def form_valid(self,form): request=self.request next_=request.GET.get('next') next_post=request.POST.get('next') redirect_path=next_ or next_post or None email=form.cleaned_data.get('email') password=form.cleaned_data.get('password') user=authenticate(username=email, password=password) if user is not None: login(request, … -
File gets uploaded but then incorrect URL is displayed in API
The working part looks this way: file = models.FileField(upload_to=upload_file) The method is defined as: def upload_file(instance, filename): return '{user}/{filename}'.format(user=instance.user, filename=filename) In settings.py I have the following paths set: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') MEDIA_URL = '/media/' (...) # For reference: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } After uploading a file through admin interface there is a success message and the file appears in static/media/admin/<file> location. The static directory is in BASE_DIR, at the same level as db.sqlite3 mentioned in the excerpt above. However, when displaying image location in API, I'm getting something like: "file": "http://127.0.0.1:8000/media/uploads/admin/<file>" As you clearly see, the static directory is skipped and I get 404 after clicking the link. What should be fixed to make it work in Django 2.2? -
Dynamically modifying fields: empty validated_data
Hello everyone ! So to start here is the behavior on one of the endpoint, I am working on: # GET # "id": 1, # "name": "test", # "created_date": "date", # "completed_date": "date", # "template": { "name" : "test" } => nested serializers with only the field "name" # "status": 1, # "results": [ { __all__ }, ... ] => nested serializers with all the fields # "groups": [ # { "name" }, ... => nested serializers with only the field "name" # ] # POST # "name": "test", # "template": {"name":"test"}, # "groups": [ # {"name":"test"} # ] As you can see, the POST and GET request have some of the field as read_only (status, results, events) and nested fields only require the "name" field not all of them. Here is the Serializers for this endpoint: class CampaignsSerializer(serializers.ModelSerializer): template = TemplatesSerializer(fields=('name')) results = ResultsSerializer(many=True, read_only=True) groups = GroupsSerializer(many=True, fields=('name')) class Meta: model = Campaigns fields = ('id', 'user_id', 'name', 'created_date', 'completed_date', 'template', 'status', 'results', 'groups', ) read_only_fields = ('status', 'results', ) def create(self, validated_data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user template = Templates.objects.filter(name=validated_data.pop('template')).first() groups = validated_data.pop('groups') campaign = Campaigns.objects.create(user_id=user.id, template=template.id, **validated_data) … -
Python function is only working once after the start of the server on Django
When using my django page, i use a function that calculate the size of a folder during the run of a job, i use that do display it on the page. But after some tests this function only works once after i run the server, after that it affects "0" to folder_size everytime. I need it to work everytime so i can affect the value to my model during the job. Do anyone have any idea about a way to solve that ? Here is the function : def size_folder(folder_path): folder_size = 0 print(folder_path) for (path, dirs, files) in os.walk(folder_path): for file in files: filename = os.path.join(path, file) folder_size += os.path.getsize(filename) folder_size = folder_size / (1024* 1024.0) if (folder_size < 1) : folder_size = round(folder_size, 5) else : folder_size = round(folder_size, 2) folder_size = str(folder_size) + " MB" return(folder_size) -
Not able to Upload File using Django Forms
I am trying to upload File using Djano-form but it's not working. but when i am trying to upload using admin it's working fine.please help me please help me................................................................................................................................ Models.py from django.db import models class certificateDb(models.Model): Dev = 1 QA = 2 UAT = 3 Production = 4 environment_TYPES = ( (Dev, 'Dev'), (QA, 'QA'), (UAT, 'UAT'), (Production, 'Production'), ) application = models.CharField(db_column='Application', max_length=255, blank=True, null=True) # Field name made lowercase. startdate = models.DateField(null=True) expiredate = models.DateField(null=True) environment_type = models.PositiveSmallIntegerField(choices=environment_TYPES) file=models.FileField(upload_to='',null=True,blank = True) forms.py from django import forms from SharedApps_Application.models import certificateDb from django.forms.fields import DateField class CertificateForm(forms.ModelForm): startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) class Meta: model = certificateDb fields = ('application', 'startdate', 'expiredate', 'environment_type','file' ) view.py from SharedApps_Application.models import certificateDb from SharedApps_Application.forms import CertificateForm from django.http import JsonResponse from django.template.loader import render_to_string def list(request): certificatedata = certificateDb.objects.all() context = { 'certificatedata': certificatedata } return render(request, 'list.html',context) def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True certificatedata = certificateDb.objects.all() data['list'] = render_to_string('list_2.html',{'certificatedata':certificatedata}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) def certificate_create(request): if request.method == 'POST': form = CertificateForm(request.POST, request.FILES or None) … -
How do I let users do backup and restore of database in Django multi tenant application using PostgreSQL for database?
I am building a multi-tenant Django web application. I want to add the option of the database-schema backup and restore for each schema, so a user can backup and restore their schema or app on their own. I was able to make the backup option for each schema. So any user can back up their DB-schema but for the restore part, I could not figure out what and how should I do? I want to add the menu for backup and restore. On click, DB-schema will be backed up and downloaded to the user's computer and to restore that, a user should be able to upload the backed-up DB-schema and restore it. I am using PostgreSQL with Django multi-tenancy. A single database with multiple schemas. -
Django An existing connection was forcibly closed by the remote host
I am googling a lot to find the solution. Maybe this is windows or python bug. I am here for getting help. It is creating problem while debuging. Traceback (most recent call last): File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 258, in send_preamble self._write(('Server: %s\r\n' % self.server_software).encode('iso-8859-1')) File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 803, in write self._sock.sendall(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host [19/Apr/2019 14:31:19] ERROR [django.server:154] "GET /static/node_modules/metronic-theme-classic/assets/media/logos/favicon.ico HTTP/1.1" 500 59 Exception happened during processing of request from ('127.0.0.1', 52183) Traceback (most recent call last): File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 258, in send_preamble self._write(('Server: %s\r\n' % self.server_software).encode('iso-8859-1')) File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\azad\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 803, in write self._sock.sendall(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host During handling of the above exception, another exception occurred: Traceback … -
How to parse raw json response from API (displayed on browser)
I'm writing web application in Django with Python3.6 which request GET from API on other host. Django+mod_wsgi+httpd. I get raw json response on browser: {"version":"3.3.2","level":"SP2","system":"unix","server_time":"1555661141000","server_utc":"2","multinode_enabled":"NO","cg_enabled":"NO","instance_id":"hostname"} My views.py is: def about(request): response = requests.get( 'https://hostname.net:8081/abc/api/v1/about', verify='/certs/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxx'}, ) return HttpResponse(response.content) I am wondering is and if yes, how to parse this response so the view in browser will be something like: version: 3.3.2 level: SP2 system: unix server_time: 1555661141000 server_utc: 2 multinode_enabled: NO cg_enabled: NO instance_id: hostname should this be parsed in .../templates.../*.html file? or within vievs.py? -
Can not run raw query in django
I have a sql which runs on postgres client (Postico), but when I put it in the django raw query, it returns syntax error. CREATE OR REPLACE FUNCTION MaxDate(d1 timestamp with time zone, d2 timestamp with time zone) RETURNS timestamp with time zone AS $$ BEGIN IF d2 > d1 THEN RETURN d2; END IF; RETURN d1; END $$ LANGUAGE plpgsql; this is the error: django.db.utils.ProgrammingError: syntax error at or near " IF" LINE 7: IF d2 > d1 THEN RETURN d2; this is test query select MaxDate(now(), now()+'1 day'::interval) -
TypeError while migrating the models in postgresql
django-cms When i tried to perform python manage.py migrate in postgresql it is returning a TypeError but it is not giving any error in sqlite3. ... File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/cms/migrations/0019_set_pagenode.py", line 68, in apply connection.introspection.get_table_description(connection.cursor(), 'cms_page') File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/db/backends/postgresql/introspection.py", line 87, in get_table_description )) for line in cursor.description File "/home/vagrant/.virtualenvs/pmvp/lib/python3.6/site-packages/django/db/backends/postgresql/introspection.py", line 87, in )) for line in cursor.description TypeError: sequence index must be integer, not 'slice' -
Django CRUD app example/plugin for consuming external REST API?
I have just started to learn django. I don't need to Create and API e.g. I will NOT be using Django REST Framework. Are there any best practice or django plugin app which shows you how to consume external REST API in a best practice manner? My goal is to create CRUD like application using/consuming external REST API? Any suggestions? -
When overriding change_form.html template in Django Admin, the breadcrumb for its model listview is grayed out and unclickable
For some reason when overriding the change_form.html template in Django Admin, its associated listview breadcrumb is grayed out and you can't click on it. Does anyone know how to make it available again? Thank you. -
set the value of status to 'live' on my database
I'm working on an application that uses Angular for the front and Django for the back. My database contains a table named 'api_match' which contains the field 'status', this field describes the status of a football match, it could be live, closed, not_started ... In the frontend of my application, the user can submit a form that will update this database, but if in my database the status field is set to 'live' (api_match.status == 'live') I want the value to remain the same even if the user tries to change it to another status. I managed to tackle this, by sending multiple requests to the back to check the value of status while the user is updating the form. but It's not efficient. Now I am looking for another solution that will enable me to keep the status field set to 'live' when the user is trying to update this value but in a more efficient way. I am new to Django and I will appreciate your help! -
How to download archive and get xml file from it using requests python?
I need to download zip archive from web page and then to get xml file from this archive to parse it via using requests python? -
Import JSON records into database on Django and performing CRUD on JSON file
1) I have a JSON file (structure as seen below) and it has hundreds of records. How can I put these data into my Django model so that I am able to perform CRUD operations on the data? I do not want to change the structure of the JSON file to match the output given by Django's model files as it can be tedious. 2) Please advise as I am also unsure where to put my JSON files in the project as well. [ { "name": "A", "abbreviation": "a", "count": 1 }, { "name": "B", "abbreviation": "b", "count": 3 }, { "name": "C", "abbreviation": "c", "count": 55 } . . . ] I am new and using Django 2.2 and I just finished "TheNewBoston" Django tutorial. I am using Django's model to makemigration and migrate to my database. I think I am using SQLite which is the default for Django. Below is my code for my model. class userDetail(models.Model): name = models.IntegerField(max_length=20) abbreviation = models.CharField(max_length=2) count = models.IntegerField() -
How to fetch all products without the hidden(private) ones with woocommerce api in python-django?
Having an eshop building with wordpress, i am using the woocommerce api in order to fetch my products in my django app. I find difficulty in fetching all the products without the hidden - private. The hidden-private products are those which are not visible in my eshop. Is there a way through api to fetch all without the hidden? Here is my code fetching all the products: wcapi = API( url=something, consumer_key=something, consumer_secret=something, wp_api=True, version="wc/v2", query_string_auth=True, verify_ssl = True, timeout=10 ) #take all the products from the woocommerce api r=wcapi.get("products") -
What is wrong with my nested for Loop in a django Template?
I am trying to create a template with Django that loops through Posts and for each Post loops through all Pictures. I already looked at some answers to other Questions but I can not find my error. Models: class Post(models.Model): Post_Title = models.CharField(max_length=200) Post_pub_date = models.DateField('date published') Post_Author = models.CharField(max_length=100) Post_Text = models.TextField() def __str__(self): return self.Post_Title class Picture(models.Model): Post = models.ForeignKey(Post, on_delete=models.CASCADE) Picture = models.ImageField() Picture_Name = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.Picture_Name Views: class PostView(generic.ListView): template_name = 'myblog/index.html' context_object_name = 'Post_List' def get_queryset(self): """ Returns Posts """ return Post.objects.order_by('-Post_pub_date') Template: {% for Post in Post_List %} <h1 class="mb-4">{{Post.Post_Title}}</h1> <span class="category">{{Post.Post_Author}}</span> <span class="mr-2">{{Post.Post_pub_date}}</span> <div class="post-content-body"><p>{{Post.Post_Text}}</p> {% for Picture in Post.Picture_set.all %} <div class="col-md-12 mb-4 element-animate"> <h2>{{Picture.Picture_Name}}</h2> <img class="col-md-12 mb-4 element-animate" src="{{ MEDIA_URL }}{Picture.Picture}}"> </div> {% endfor %} </div> {% endfor %} The Post_Title, Post_Author, Post_pub_date and Post_Text are displayed fine. Just the nested For loop is not producing any Picture_Name or Picture as if the Picture_set.all is empty. As mentioned above I tried to find my error in different Posts like this but could not find it. Thanks for your help. -
How to add choice field in UserCreationForm based class?
i have a question that how i can add ChoiceField in class UserCreationForm. i have tried to add but the issue is "too many values to unpack (expected 2)", i dont know why. i have the code below. Thanks for helping my model.py class Viewer(models.Model): INTERESTS_CHOICES = ( ('IT', 'IT'), ('MARKETING', 'marketing'), ('BUISINESS', 'buisiness'), ('DESIGN', 'design'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) interests = models.CharField(choices=INTERESTS_CHOICES, max_length=8, default='IT') def __str__(self): return self.user.username my forms.py INTERESTS_CHOICES = ( ('IT', 'IT'), ('MARKETING', 'marketing'), ('BUISINESS', 'buisiness'), ('DESIGN', 'design'), ) class ViewerRegisterForm(UserCreationForm): email = forms.EmailField(required=False) interests = forms.ChoiceField(choices=[INTERESTS_CHOICES]) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] @transaction.atomic def save(self): user = super().save(commit=False) user.is_viewer = True user.save() viewer = Viewer.objects.create(user=user) return user -
Prefetching indirectly related items using Django ORM
I'm trying to optimize the queries for my moderation system, build with Django and DRF. I'm currently stuck with the duplicates retrieval: currently, I have something like class AdminSerializer(ModelSerializer): duplicates = SerializerMethodField() def get_duplicates(self, item): if item.allowed: qs = [] else: qs = Item.objects.filter( allowed=True, related_stuff__language=item.related_stuff.language ).annotate( similarity=TrigramSimilarity('name', item.name) ).filter(similarity__gt=0.2).order_by('-similarity')[:10] return AdminMinimalSerializer(qs, many=True).data which works fine, but does at least one additional query for each item to display. In addition, if there are duplicates, I'll do additional queries to fill the AdminMinimalSerializer, which contains fields and related objects of the duplicated item. I can probably reduce the overhead by using a prefetch_related inside the serializer, but that doesn't prevent me from making several queries per item (assuming I have only one related item to prefetch in AdminMinimalSerializer, I'd still have ~2N + 1 queries: 1 for the items, N for the duplicates, N for the related items of the duplicates). I've already looked at Subquery, but I can't retrieve an object, only an id, and this is not enough in my case. I tried to use it in both a Prefetch object and a .annotate. I also tried something like Item.filter(allowed=False).prefetch(Prefetch("related_stuff__language__related_stuff_set__items", queryset=Items.filter..., to_attr="duplicates")), but the duplicates property is added to … -
Upload Image in Django Rest
Want to save image in django backend but it gives me error: "non_field_errors": [ "Invalid data. Expected a dictionary, but got tuple." ] I am using django rest framework when I try to save image and input data using json format it gives me non field errors.Below is the format in which I am giving data JSON data format { "title": "Open cv detection", "description": "abc", "main_image": "watch2.PNG", "videourl": null, "project_rank": 1, "category": 1 } Here main image is the image I want to upload.I think I am using a wrong way to give image path can anyone tell how to give proper or upload image in json forma Views.py: class CreateProject(APIView): def get(self,request): return Response(ProjectCreateSerializer(project).data for project in Project.objects.all()) def post(self,request): payload=(request.data,request.FILES) serializer=ProjectCreateSerializer(data=payload) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) Serializer.py class ProjectCreateSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' def create(self, validated_data): project = Project.objects.create(**validated_data) return project def update(self, instance, validated_data): for k, v in validated_data.items(): setattr(instance, k, v) instance.save() return instance -
Django I want to get avatar from Twitter but it fails
Django2.1 I have implemented twitter authentication in social-auth-app-django. I want to get an avatar for login account, but it doesn't work. I added a pipeline referring to this Japanese page, but I get an error. What is the reason?It works fine before writing a pipeline. ModuleNotFoundError at /complete/twitter/ No module named 'myapp.users' my code #settings.py SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'myapp.users.pipeline.get_avatar', ) #pipiline.py def get_avatar(backend, strategy, details, response, user=None, *args, **kwargs): url = None if backend.name == 'twitter': url = response.get('profile_image_url', '').replace('_normal', '') if url: user.profile.avatar = url user.save() #models.py from django.contrib.auth import get_user_model from django.db import models def get_myapp_image_path(instance, filename): return 'image-{0}/{1}'.format(instance.id, filename) class Social(models.Model): user = models.ForeignKey(get_user_model(), related_name='socials', on_delete=models.CASCADE) provider = models.CharField(max_length=32) uid = models.CharField(max_length=255) class Meta: unique_together = ('provider', 'uid') db_table = 'socials' class Myapp(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) username = models.CharField(max_length=30, unique=True, primary_key=True) title = models.CharField(max_length=20) content = models.TextField(max_length=500) avatar = models.URLField(max_length=200, blank=True) posted_date = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if not self.username: self.username = self.user.username super(Myapp, self).save(*args, **kwargs) thank you. -
Saving model instance using pre_save signal
These are my models: class Stockdata(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='user_stock') company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True) stock_name = models.CharField(max_length=32) class Stock_journal(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='user_closing') company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True) stockitem = models.OneToOneField(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='closingstock') closing_stock = models.DecimalField(max_digits=10,decimal_places=2,null=True) This is my signal: @receiver(post_save, sender=Stockdata) def create_default_stock_ledger(sender, instance, created, **kwargs): if created: Stock_journal.objects.create(user=instance.User,company=instance.Company,stockitem=instance) I want to pass a pre_save signal of the same as I have done in my post_save signal i.e. I want to perform a pre_save signal function instead of a post_save signal.. When I try to do using pre_save signal I get the following error: save() prohibited to prevent data loss due to unsaved related object 'stockitem'. Any idea how to do this? Thank you -
It is posible to get output of external barcode scanner to Django
In my project I have external bar-code scanner, I want get scanner output on my django project, is this possible? if any have article or blog please share