Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call a request inside a class in view
I am new to Django. I need to set the foreign key as current signed in user for a post model but it says the NOT NULL constraint failed: posts_post.author_id django I dont know why. class UserRegistraionModel(models.Model): post = models.CharField(max_length=5000, blank=False, null=False) image = models.ImageField(upload_to='media', blank=False, null=False) author = models.ForeignKey(User, on_delete=models.CASCADE) I don't know what is the error how can I solve this. Thanks in advance. -
Meaning of these lines (python, django and channels)
I was messing aroung with django channels, and I was wondering how can I add a user to a chat, so I've come across this answer in stackoverflow: How to add members to same chat room in Django Channels 2.1.1 using multichat example But then I came across these lines and I realized that I don't understand them: '''if staff in users_and_rooms and len(users_and_rooms[staff]) in range(3):''' '''await channel_layer.send(users_and_channels[random_available_staff], content)''' '''users_and_channels[random_available_staff],''' I guess 'users_and_channels' is a dictionary with value pairs being the user and his/her channel. I got that. But what about the first line? 'len(users_and_channels[staff] in range(3)' Isn't 'range' for loops? What is it doing there? And 'len(users_and_channels[staff]', it is checking the length of what? The number of channels of a user? It's a little confusing to me. Hope someone can help me. Thank you very much. And excuse my English. -
How to send data via http request in django
I was trying to make a django webapp and I can send data through the http request. I want to send the id or number to be sent on the background not on the URL my main goal was to send the data like the user object in django, so we can access the data in the html like the user object {{user}} i tried to send with the request object but i didn't work -
How to login with register api if user already exits while social authentication: Django?
I'm creating custom user social authentication system. whenever user first time login then with social account then his/her social credential will be save in db. if second time will login with social account then it's automatic will login with his/her social_id that saved in db. but in my case, whenever user first time login with social account then his/her social credential saves in db. but in second time it's showing user already exits. Any help would be much appreciated. serializers.py : class CreateSocialUserSerializer(serializers.ModelSerializer): login_type = serializers.CharField(allow_blank=True) social_id = serializers.CharField(allow_blank=True) email = serializers.CharField(allow_blank=True) phone_number = serializers.CharField(allow_blank=True) country_code = serializers.CharField(allow_blank=True) token = serializers.CharField(read_only=True) first_name = serializers.CharField(allow_blank=True) last_name = serializers.CharField(allow_blank=True) class Meta: model = User fields = ['login_type', 'social_id', 'email','phone_number', 'country_code','token','first_name','last_name', ] def validate(self,data): logger.debug(data) login_type = data['login_type'] social_id = data['social_id'] email = data['email'] phone_number= data['phone_number'] country_code = data['country_code'] #some validation logic here...... #Email Validation logic here ..... #Mobile Number Validation if phone_number.isdigit() == True: user_qs = User.objects.filter(phone_number__iexact = phone_number) if user_qs.exists(): raise APIException400({'success' : 'False','message' : 'User with this phone_number is already exists'}) else: if login_type in ['2','3','4','5','6']: if social_id: social_qs = User.objects.filter(social_id__iexact=social_id) if social_qs.exists(): raise APIException400({'success': 'False', 'message': 'User with this social_id is already exists. Please login.'}) return data return data … -
only '-' value appeared for all the data in my csv file
from django.contrib import admin from .models import NutritionModel from import_export.admin import ImportExportModelAdmin class NutritionModelAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ['sl_no', 'sub_domain', 'indicators', 'national_indicator_reference','sector', 'data_collab','variable_required','data_sources'] search_fields=['sl_no', 'sub_domain', 'indicators', 'national_indicator_reference','sector', 'data_collab','variable_required','data_sources'] filter_horizontal=() list_filter=[] fieldsets=[] admin.site.register(NutritionModel,NutritionModelAdmin) from import_export import resources class NutritionModelResource(resources.ModelResource): class Meta: model = NutritionModel resource_class = NutritionModel #models.py from django.db import models class NutritionModel(models.Model): id=models.AutoField(primary_key=True) sl_no = models.CharField(null=True, blank=True,max_length=5, verbose_name="Sl no") sub_domain = models.CharField(null=True, blank=True,max_length=5,verbose_name="Sub-domain") indicators =models.CharField(null=True, blank=True,max_length=200,verbose_name="Indicators") national_indicator_reference =models.CharField(null=True, blank=True,max_length=10,verbose_name="National indicator reference") sector =models.CharField(null=True, blank=True,max_length=20,verbose_name="Sector") data_collab = models.CharField(null=True, blank=True,max_length=100,verbose_name="Ministry/ Agencies for data collaboration") variable_required =models.CharField(null=True, blank=True,max_length=200,verbose_name="Variable required") data_sources =models.CharField(null=True, blank=True,max_length=10,verbose_name="Data sources@") -
ImportError: cannot import name 'OAuth1Session' from 'requests_oauthlib'
I am new to django framework. I tried to create a login authentication through twitter using tweepy. While saving the fetched data in my db, I am facing this issue for OAuth1Session. I have tweepy installed. I have also installed requests_oauthlib, but still doesn't able to resolve this error. from tweepy.auth import OAuthHandler #error called here (**ImportError: cannot import name 'OAuth1Session' from 'requests_oauthlib'** ) from .models import Tweet import credentials def user_tweets(): auth = OAuthHandler(credentials.CONSUMER_KEY, credentials.CONSUMER_SECRET) auth.set_access_token(credentials.ACCESS_TOKEN, credentials.ACCESS_TOKEN_SECRET) api = tweepy.API(auth) user_tweets = api.user_timeline(count=50) return user_tweets -
How can I add an instruction after an object creation in Django CreateView?
On my generic class based CreateView, I would like to perform an instruction which creates new objects from another model related to the current created object. Example: Collection is a model which is related to 3 differents Element objects. When I create a MyCollection object, which is related to a Collection and a User, 3 MyElement object must be created too and related to the newly created MyCollection object. One for each Element related to Collection. # models.py from django.contrib.auth.models import User from django.db import models class Collection(models.Model): # attributes and methods... class Element(models.Model): collection = models.ForeignKey(Collection, # more arguments...) # more attributes and methods class MyCollection(models.Model): user = models.ForeignKey(User, # more arguments...) collection = = models.ForeignKey(Collection, # more arguments...) # more attributes and methods def get_absolute_url(self): reverse(# some url with the object pk) class MyElement(models.Model): element = models.ForeignKey(Element, # more arguments...) my_collection = models.ForeignKey(MyCollection, # more arguments...) # more attributes and methods I'm using the generic CreateView from Django and after a little bit of research, I saw that it was possible to perform additional actions in the CreateView by overriding the get_success_url() method. In my example, I did something similar: # views.py from django.views.generic import CreateView from .utils … -
Django Background Image Not Working How To Fix?
I am trying to make my background image for a website I am working on but when ever I try to make it, it appears white for that page image < as you can see the page just shows white I am not sure why it happens when ever I try to add a pg image My Home Page The background line of code is the first 2 line of code <head> <style type="text/css"> body { background-image: url("ok.png"); } .sidenav2 h1 { margin-top: 190px; margin-bottom: 100px; margin-right: 150px; margin-left: 350px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav3 h1 { margin-top: -125px; margin-bottom: 100px; margin-right: 150px; margin-left: 400px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav4 h1 { margin-top: -128px; margin-bottom: 100px; margin-right: 150px; margin-left: 800px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav5 h1 { margin-top: 328px; margin-bottom: 100px; margin-right: 150px; margin-left: 800px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav6 h1 { margin-top: -130px; margin-bottom: 100px; margin-right: 150px; margin-left: 400px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav7 h1 { margin-top: -130px; margin-bottom: 100px; margin-right: 150px; margin-left: 50px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } </style> </head> < … -
Why I`m getting OSError: [Errno 7] Argument list too long: b'/usr/local/bin/git'?
I'm doing a programming course (CS50W) and it has a command to submit the project to github automatically. It's called submit50. When trying to push my code to github through this method, I do: submit50 --verbose web50/projects/2020/x/capstone And I'm getting the following error: OSError: [Errno 7] Argument list too long: b'/usr/local/bin/git' I have literally no idea what is happening here. If you could help me out I would be grateful. Full error with traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/bin/submit50", line 11, in <module> load_entry_point('submit50==3.0.2', 'console_scripts', 'submit50')() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/submit50/__main__.py", line 147, in main user_name, commit_hash, message = lib50.push("submit50", args.slug, CONFIG_LOADER, prompt=prompt) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/lib50/_api.py", line 69, in push with authenticate(remote["org"], repo=repo) as user, prepare(tool, slug, user, included): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in __enter__ return next(self.gen) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/lib50/_api.py", line 326, in prepare _run(git(f"add -f {' '.join(shlex.quote(f) for f in included)}")) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/lib50/_api.py", line 703, in _run with _spawn(command, quiet, timeout) as child: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in __enter__ return next(self.gen) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/lib50/_api.py", line 674, in _spawn child = pexpect.spawn( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pexpect/pty_spawn.py", line 205, in __init__ self._spawn(command, args, preexec_fn, dimensions) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pexpect/pty_spawn.py", line 303, in _spawn self.ptyproc = self._spawnpty(self.args, env=self.env, File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pexpect/pty_spawn.py", line 315, in _spawnpty return ptyprocess.PtyProcess.spawn(args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ptyprocess/ptyprocess.py", line … -
Does django testing have a breakDown() similar to setUp() that is ran after all tests complete?
I am running some tests in django but they depend on a response from an outside service. For instance, I might create a customer and wish to acknowledge it has been created in the outside service. Once I am done with testing I want to remove any test customers from the outside service. Ideally, there would be a method similar to setup() that runs after all tests have completed. Does anything like this exist? -
Django - Inserting initial value into ModelChoiceField
Let's go. So I have this site where users' first step is to register their company. The models.py of company is like this: class Company(models.Model): companyId = models.CharField(unique=True, max_length=20, primarykey=True) ...morefields... The forms.py is like this: class CompanyForm(forms.ModelForm): companyId = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Company ID'})) ...morefields... class Meta: model = Company fields = ('companyId', ...fields n fields...) And there's the views.py to register the company def registerCompany(request): context = {} company_form = CompanyForm(request.POST or None) if company_form.is_valid(): request.session['companyId'] = company_form.cleaned_data['companyId'] obj = company_form.save() obj.save() company_form = Company() return redirect("/accounts/register") context['company_form'] = company_form return render(request, 'register-company.html', context) In the views.py above, the companyId is being stored using sessions, it will be used later. After registering the company it's time to register the employee, which is presumed to be someone on the company's staff. The employee app is a custom user. This is how the employee models.py looks like: Class Employee(AbstractBaseUser, PermissionsMixin): ...fields n fields... company = models.ForeignKey(Company, default=None, blank=True, null=True, on_delete=models.CASCADE) ...custom user stuff... ps: Custom User is working fine, the problem doesn't seem to be related to this The Employee's forms.py: class RegistrationForm(UserCreationForm): company = forms.ModelChoiceField(initial='class', queryset=Company.objects.all()) class Meta: model = Employee fields=(fields n fields, "company") ps: these 'fields n fields' all have … -
The view profiles.views.ProfileDetailComment didn't return an HttpResponse object. It returned None instead
I am trying to process a form in generic detail view. I am using this django doc to make this view. In this view I am showing all the info and post by the profile model. and anyone visiting this profile can comment on the post of this profile Here is my view: from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import gettext_lazy as _ from django.views import View from django.views.generic import DetailView, RedirectView, UpdateView, FormView from django.views.generic.detail import SingleObjectMixin from .models import Profile from posts.forms import PostModelForm, CommentModelForm from posts.models import Post from relationships.models import Relationship User = get_user_model() class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile slug_field = "slug" slug_url_kwarg = "slug" form_class = CommentModelForm queryset = Profile.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) sender_profile = get_object_or_404(Profile, id=self.request.user.id) receiver_profile = get_object_or_404(Profile, id=self.object.id) frnd_btn_state = Relationship.objects.relation_status( sender=sender_profile, receiver=receiver_profile, ) context['frnd_btn_state'] = frnd_btn_state context['frnd_req_rcvd'] = Relationship.objects.invitation_recieved( receiver = sender_profile ) context['form'] = CommentModelForm() return context class ProfilePostComment(SingleObjectMixin, FormView): template_name = 'profiles/profile_detail.html' form_class = CommentModelForm model = Profile def post(self, request, *args, **kwargs): comment_form = CommentModelForm() profile=Profile.objects.get(user=request.user) if 'submit_c_form' in request.POST: comment_form = CommentModelForm(request.POST or None) if … -
Django app works locally but not when deployed with Caddy
I am trying to get a chatbot running using a web interface with the help of Django. Locally this code works perfectly fine: app = Flask(__name__) app.static_folder = 'static' @app.route("/") def home(): return render_template("index.html") @app.route("/get") def get_bot_response(): userText = request.args.get('msg') return str(chatbot.get_response(userText)) if __name__ == "__main__": app.run() When I access localhost:5000 I can interact with the bot. However, when I deploy it on my university's virtual machine using the following caddyfile, the bot does not reply: *name of my virtual machine*.cs.ucl.ac.uk tls *my username*@ucl.ac.uk root *path to chatbot directory* proxy /chatbot localhost:5000 { transparent without /chatbot except /static } I know that the callback URL works because I have hosted chatbots on facebook before using the same flask framework and the same caddyfile (without "except /static"), with the help of Facebook's send/receive API. Any idea what I am doing wrong? I am a researcher with 0 experience in web development and will appreciate any help -
Django trigger an event on server stopped
I have a Django server (running on built-in server-container). Want to do something before app shutdown. Is there a way to trigger an event when server (or whole app) stopped/terminated. -
how to pass multiple context in django?
in line number 11 to 14 have two parameters why_choose_uss and Servicess i want to pass this two parameters in laxmi/index.html -
Data from views in Django is not showing in Django template
I was in middle of developing my E - commerce website using Django. Everything was working file unless I found a strange bug while Developing this website. So lets come to the Problem When I am trying to send a Dictionary to Django Template it is not showing the values in the Template I have Attached snapshot of my Code. Please tell me How to solve this bug Click Here to see my Python Code Click here to see the Django template code Click here to see the result that the Python code is working correctly but the Django template have a error ( I feels like this ) Please tell me where I am wrong -
How to create user with automatic default fields
I am not sure how to phrase this but I have the User from the user model given by django.contrib.auth.models I can register, login, and logout a user but now I would like to do a bit more. I want to have a wallet that the user is associated with upon registering. So far what I did was create a separate app called wallets and my model looks like... class Wallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) cash = models.FloatField(default=100, blank=True) The idea is that instead of extending my User model class to have another field being that I am using the existing User model already I am doing a OneToOneField(User) so that a user is associated with a wallet and that wallet containing the default amount of cash of 100 dollars When I create a user I want the wallet to be created and linked to that user as well. How do I do this? -
Is there any open source code available for a free lance platform in django?
I'm looking for a open code for a free lance platform in Django but so far I have not found anything. Are there any leads? -
how can i merge two forms fields in Django?
Is there a concept where two forms fields can be merged together? I want the output in a single {{ forms }}. i want to merge the ResultForm field(result_values) into LessonForm fields! please tell me if anybody know the concept? forms.py class LessonForm(forms.ModelForm): class Meta: model = Lesson fields = [ 'name', 'expected_values' ] class ResultsForm(forms.ModelForm): class Meta: model = Results fields = ['result_values'] -
django template comparing data from file executing wrong code path
I have a file /tmp/something.txt the contents of the file have the following is just simply a 1 In my view I have the following class StrippedView(AccessRequired, TemplateView): template_name = 'stripped' title = 'stripped' def get_context_data(self, **kwargs): with open('/tmp/something.txt','r') as file: data = file.read() context = super(stripped, self).get_context_data(**kwargs) context['title'] = self.title context['something'] = data return context And here is what I have in my template <tr> <th> Activate </th> {% if something == 1 %} <td> <a class="btn btn-warning btn-sm" href="{% url 'system:stripped' %}"><b>{% bootstrap_icon 'lock' %} Deactivate</b></a> </td> {% else %} <td> <a class="btn btn-primary btn-sm" href="{% url 'system:stripped' %}"><b>{% bootstrap_icon 'lock' %} Activate</b></a> </td> {% endif %} </tr> So here is what I expect to happen When the file has a 1 in it then the first button displays that says activate and if the file has anything else then it will display the Activate button What did happen Instead what is happening is it is always display the Activate button What have I tried At first I wanted to know what was actually being returned so I replaced the text of the activate button with the variable like so <a class="btn btn-primary btn-sm" href="{% url 'system:https' %}"><b>{% … -
Logging in a user Django REST
I am using Token Authentication, I want to add a Login and Logout Endpoint to my Api I am using Django REST My code: serializers.py #Login class UserLoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): email = data.get("email", "") password = data.get("password", "") if(email and password): user = authenticate(email= email, password= email) #If user credintials are correct if(user): if(user.is_active): data["user"] = user else: raise serializers.ValidationError("User Is Deactivated!") else: raise serializers.ValidationError("Unable To Login with given Email/Password!") else: raise serializers.ValidationError("Must Provide Email / Password!") return data views.py: #Login class UserLoginView(GenericAPIView): serializer_class = UserLoginSerializer def post(self, request): serializer = UserLoginSerializer(data= request.data) serializer.is_valid(raise_exception= True) user = serializer.validated_data["user"] login(request, user) token, created = Token.objects.get_or_create(user= user) return Response({"token": token.key}, status= status.HTTP_200_OK) My Question is: The problem that I am facing is whenever I login a user, I get the following message: "Unable To Login with given Email/Password!", Although the right credentials were provided. What might the problem be? Thanks. -
template code not working in different app template
I try to learn Django, I'm sure that my question is stupid but I think every beginner must pass this route to success, of course with the help of pro's. Also, I have a site with 2 app's, profiles and posts In this project I can see who I'm following in a list in template (posts/main.html) the problem is that I need the same list also in the other template (profiles/main.html). I have made a copy of the piece of code but it doesn't worked. I really don't know how to explain it better or I don't know how I can search it exactly. I tried this : 1.) How to use views in different apps templates 2.) How to import views from other apps views 3.) and a lot more, I read all the stuff but I couldn't find what I'm looking for Thanks a lot for your help. POSTS APP posts/models.py class Post(models.Model): ... author = models.ForeignKey(Profile, on_delete=models.CASCADE) text = models.TextField(default='no text...') ... def __str__(self): return str(self.text)[:30] posts/urls.py from django.urls import path from .views import posts_of_following_profiles, index, contact, about, category, PostListView, PostDetailView, post, detay from profiles.views import ProfileListView app_name="posts" urlpatterns = [ ... path('following/', ProfileListView.as_view(), name='posts-follow-view'), ... ] … -
Serialize Dictionary Object Where Keys Are Different
I have a dictionary object which has the days of the week as keys. Please can someone advise if there is a way to serialize this object using a Django Serializer. The example dictionary output looks like this: [{'mon': {'AM': False, 'PM': False}}, {'tue': {'AM': True, 'PM': False}}, {'wed': {'AM': False, 'PM': False}}, {'thu': {'AM': True, 'PM': True}}, {'fri': {'AM': False, 'PM': True}}, {'sat': {'AM': False, 'PM': False}}, {'sun': {'AM': False, 'PM': False}}] The closest I can get is having serializer method fields for each day of the week, but that returns null for every weekday which is not part of the set. I have tried: class SlotSerializer(serializers.Serializer): AM = serializers.BooleanField() PM = serializers.BooleanField() class SchoolSlotSerializer(serializers.Serializer): mon = serializers.SerializerMethodField(required=False) def get_mon(self,obj): if obj.get('mon'): return SlotSerializer(obj['mon']).data #Repeated for each weekday -
Why does my form error not show up in the template?
I have a user login form class PersonLoginForm(forms.Form): username = forms.CharField(max_length=20, required=True) password = forms.CharField(max_length=100, required=True) def clean_password(self): user = Person.objects.get(username=self.cleaned_data['username']) if not user.check_password(self.cleaned_data['password']): self.add_error('password', 'That password is incorrect!') return self.cleaned_data In there I check if the password is correct so that I can let an error message appear in the template I access the error message in my template like so <div class="field-wrapper"> {% render_field form.password.errors %} {% render_field form.password.label_tag %} {% render_field form.password placeholder='password...' type='password'%} </div> but The error message does not show up! This is the view for the login form def user_login(request): if request.method == 'POST': form = PersonLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.success(request, 'Successfully logged in!') return redirect('all_users') print(form.errors) form = PersonLoginForm() context = { 'form': form, 'title': 'Login', } return render(request, 'index/login.html', context) I print it after form.is_valid() evaluates to False <ul class="errorlist"><li>password<ul class="errorlist"><li>That password is incorrect!</li></ul></li></ul> It doesn't even show up in the template -
How can I use Django DeleteView in my template
I am using Django DeleteView in a template and I've created a url & view. But it shows "Generic detail view EmployeeDeleteView must be called with either an object pk or a slug in the URLconf." I was looking on django docs, and looks like that DeleteViews are coupled with the models. How can I use Django DeleteView here. If any one help me please. views.py class EmployeeDeleteView(DeleteView): model = Employee success_url = 'create_employee' def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) urls.py path('delete_employee/<int:id>', EmployeeDeleteView.as_view(), name='delete_employee'), Delete Button <button class="deletebtn show-form-delete" type="submit"> <i class="fa fa-trash-o"></i>&nbsp;<a onclick="return confirm('Are you sure do you want to delete {{i.name}}')" href="{% url 'delete_employee' i.id %}">Delete</a></button>