Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Even After Deleting the migrations in django, old app name shows up?
The login_user app, was never created for this project. And when I run makemigrations for, I get the following error ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'login_user.user', but app 'login_user' isn't installed. Full stacktrace to migrate command (skincurate) ➜ python manage.py migrate admin /home/sshivaditya/Projects/Updated_code_3/Skincurate_Research Operations to perform: Apply all migrations: admin Running migrations: Applying admin.0004_auto_20220825_1517...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 232, in handle post_migrate_state = executor.migrate( File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/backends/sqlite3/schema.py", line 137, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "/home/sshivaditya/miniconda3/envs/skincurate/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 507, in alter_field new_db_params … -
How to make a triple sub-layers Choicefiled in Django?
I noticed that the official document has mentioned two-layer choiceFiled only. When I code a three-layer data structure, a notification pops out. (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. .e.g.: choices=( ("city", ( ("USA", "USA"), ("Canada", "Canada"), ("UK", ( ("England": "England",) ("Scotland": "Scotland"), )), )), ), Can you give me an example how to customer a widget to address this job? -
How to get innerhtml of dragged element on button onclick?
Basically I have created a drag and drop html template with javascript,what I want is get the inner html of dragged element in button onclick('') automatically to run a function, means what ever is dragged add name of element in button onclick(''). please help me with this.. <button class="btn btn-primary pull-right" id="show_graph">SHOW</button> JavaScript code $('.drag').draggable({ appendTo: 'body', helper: 'clone' }); $('#dropzone').droppable({ activeClass: 'active', hoverClass: 'hover', accept: ":not(.ui-sortable-helper)", drop: function (e, ui) { var $el = $('<div class="drop-item"><details><summary>' + ui.draggable.text() + '</summary><div><label>More Data</label><input type="text" /></div></details></div>'); $el.append($('<button type="button" class="btn btn-default btn-xs remove"><span class="fa-solid fa-trash text-white "></span></button>').click(function () { $(this).parent().detach(); })); $(this).append($el); } }).sortable({ items: '.drop-item', sort: function () { $(this).removeClass("active"); } }); Here is for loop used with help of Django and these are the draggable elements. {% for item in head %} <div class="col-12"> <a class="border border-light btn att1 btn-default drag text-white my-2">{{item}}</a> </div> {% endfor %} -
Django model.objects.get() isn't looking by param that I specify
I'm trying to get object from db. That's my model: class Employee(models.Model): class EmployeeRole(models.TextChoices): DEFAULT = 'Default' PM = 'PM' ADMINISTRATOR = 'Administrator' name = models.CharField(max_length=127, blank=False, null=False) surname = models.CharField(max_length=127, blank=False, null=False) login = models.CharField(max_length=127, blank=False, null=False) password = models.CharField(max_length=1023, blank=False, null=False) email = models.EmailField() employee_role = models.CharField(max_length=31, choices=EmployeeRole.choices, blank=False, null=False) salary = models.DecimalField(max_digits=10, decimal_places=2) department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) last_login_date = models.DateField(auto_now=True) created_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.name} {self.surname} - {self.employee_role}" That's my urls: urlpatterns = [ path('employees/<int:pk>', views.employee_details), path('employees/', views.employee_list_or_add), ] And that's my views: @csrf_exempt def employee_list_or_add(request): if request.method == 'GET': employees = Employee.objects.get(id=4) serializer = EmployeeSerializer(employees) print(serializer) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = EmployeeSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) I'm learning with REST documentation, I'm on first chapter - serialization. But I can't get any objects from db. No matter if I use Employee.objects.all() (with many=True in serializer) like in documentation or Employee.objects.get(pk=4) like currently in my code - I'm always getting error invalid literal for int() with base 10: b'17 21:19:04.767380' That's the time of last_login_date of first record in Employee db. But in .get() function I specified 'pk' so why it's … -
Accessing a parent model attribute within Django template
I have an app that has a list of projects, and each project has a number of posts, and when you click on a project, it shows all of the posts in that project, but I can't figure out how to make it display what project the user is currently on, sample of it not working It should say "Posts for project 1" for example. Here is the relevant code of what I have so far. <h1 class="mb-3">Posts for {{ post.project.title }}</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title">{{ post.title }}</a></h2> <p class="article-content">{{ post.description }}</p> </div> </article> {% endfor %} class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField(default='') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-detail', kwargs = {'pk': self.pk}) class Post(models.Model): def get_default_action_status(): return Project.objects.get(title="bruh") project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='posts', default=get_sentinel_exam_id) title = models.CharField(max_length=100) description = models.TextField(default='') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) LOW = '!' MED = '!!' HIGH = '!!!' YEAR_IN_SCHOOL_CHOICES = [ (LOW, '!'), (MED, '!!'), (HIGH, '!!!'), ] severity = models.CharField( max_length=3, … -
I need to send mail for more than one member in django
I need to send an email to the users associated to the Shop when a purchase is done in the shop. If two users was associated for two of them also email should go. Note: shop_user is the feild name and it is a many to many feild def generate_invoice(request): if request.user.is_authenticated: billingshop = shop.objects.all() Product = product.objects.all() if request.method == 'POST': form = Invoicing(request.POST) if form.is_valid(): user = form.save(commit=False) Billing_shop = form.cleaned_data['Billing_shop'] Supplier = form.cleaned_data['Supplier'] Payment_mode = form.cleaned_data['Payment_mode'] Upi_transaction_id = form.cleaned_data['Upi_transaction_id'] products = form.cleaned_data['Product'] Quantity = form.cleaned_data['Quantity'] shoping_product = product.objects.filter(Product_name= products).first() sub_total = shoping_product.product_price * Quantity user.Gst = (18 / 100)*sub_total user.Price = sub_total + user.Gst user.save() shoppingcartuser= shop.objects.get(shop_name= Billing_shop) // Match the shop name shoppingcartemails= shoppingcartuser.shop_users.all().values_list('email', flat=True) // Retriving the email address associated with the shopname in the feild name shop_users. date = datetime.today() html_content = render_to_string("invoices/invoice_email.html", {'title':"test mail","date":date,"invoiceuser":Billing_shop,"supplier":Supplier,"payment":Payment_mode,"transactionid":Upi_transaction_id}) text_content = strip_tags(html_content) email = EmailMultiAlternatives( "Congratulations! Invoice generated successfully", text_content, settings.EMAIL_HOST_USER, [shoppingcartemails] // this place is the to email ) email.attach_alternative(html_content,"text/html") email.send() messages.success(request, 'Registration successful.') return redirect('home') else: form = Invoicing() return render(request, 'invoices/create_invoice.html', context={'form': form,'shop':billingshop,'Product':Product}) else: messages.error(request, 'Please login into your account.') return render("login") The feild shop_users consists of two mail addresses and i am facing this … -
Django Testing Using AsyncClient and Authentication
I have a basic Asynchronous Class Based View: class AsyncAuthenticationView(View): async def post(self, request, *args, **kwargs): authenticated: bool = await sync_to_async(lambda: request.user.is_authenticated)() if not authenticated: return HttpResponse('Unauthorized', status=401) return HttpResponse('Success', status=200) And two simple tests: @pytest.fixture def authenticated_async_client(user) -> AsyncClient: client = AsyncClient() client.force_login(user) return client class TestAsyncAuthenticationView: @pytest.mark.asyncio async def test_with_async_client(self, authenticated_async_client: AsyncClient): """This test fails, with response code 401 instead of 200""" response = await authenticated_async_client.post( reverse('auth-test'), 'abc', content_type="text/html", ) assert 200 == response.status_code # fails with 401 @pytest.mark.asyncio async def test_with_async_request_factory(self, async_rf: AsyncRequestFactory, user): """This test succeeds correctly with response code 200""" r = async_rf.post('/fake-url', 'abc', content_type='text/html') r.user = user r.session = {} response = await AsyncAuthenticationView().post(r) assert 200 == response.status_code The first test which uses the AsyncClient always fails to authenticate returning status code 401 while the second test is passing just fine with status code 200. Based on the docs the AsyncClient has all the same methods, so I am not not why the test is failing. Perhaps there is a different authentication method that needs to be used? The AsyncRequestFactory that is being used in the second test is from the pytest-django package. Any help would be much appreciated. Thank you. -
Get user's operating system in Django & Docker
Operating system is always set to Ubuntu even in my localhost. I don't know if this is related to Docker or something else but here is my code. I have a utility function to get user's operating system (I am using httpagentparser) def get_operating_system(request): agent = request.META.get("HTTP_USER_AGENT") operating_system = httpagentparser.detect(agent).get("os").get("name") return operating_system and calling this function in my auth (sign up) view. class SignUp(FormView): form_class = SignUpForm template_name = "project1/registration/signup.html" def form_valid(self, form): user = form.save(commit=False) user.username = form.cleaned_data.get("username") user.operating_system = get_operating_system(self.request) user.save() send_email_confirmation(user, user.email) notifications.info( self.request, _( "some text here" ), ) return redirect("login") and here is my user model ... operating_system = models.CharField(_("operating system of the user"),max_length=150, default=OperatingSystem.WINDOWS) ... class User(AbstractUser): class OperatingSystem(models.TextChoices): UBUNTU = "UBUNTU",_("ubuntu") DEBIAN = "DEBIAN",_("debian") FEDORA = "FEDORA",_("fedora") MINT = "MINT",_("linux mint") WINDOWS = "WINDOWS",_("windows") MACOS = "MACOS",_("macos") ... I am running my project in a Docker in a Ubuntu server and when I sign up to my site, my operating system is always Ubuntu even I am using different operating systems such as Windows and MacOS. -
<FallbackStorage: request=<WSGIRequest: GET ''>>
Hi I have following setup: Views.py def employerSignupView(request): if request.method =="POST": form = EmployerSignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request,'Hooray !! you have account with us now!!') return redirect('home') else: messages.success(request, 'There has been problem registering new account with us. Please try again') form=EmployerSignupForm() form=EmployerSignupForm() return render(request, 'employerSignup.html', {'form': form}) urls.py urlpatterns = [ path('', views.home, name='home'), path('signup/employer/', views.employerSignupView, name='employerSignup'), path('signup/jobSeeker/', views.jobSeekerSignupView, name='jobSeekerSignup'), path('login/', views.user_login, name ='login'), path('logout/', views.user_logout, name='logout'), path('myaccount/',views.myaccount, name='myaccount'), ] forms.py class EmployerSignupForm(forms.ModelForm): username= forms.CharField(max_length=200, widget=forms.TextInput({"placeholder": "Username", "class": "form-control", "type": "text"})) email= forms.EmailField(widget=forms.TextInput({"placeholder": "Your email", "class": "form-control", "type": "email"})) first_name = forms.CharField(max_length=50, widget=forms.TextInput({"placeholder": "Buisness Name", "class": "form-control", "type": "text"})) last_name =forms.CharField(max_length=50, widget=forms.TextInput({"placeholder": "Type", "class": "form-control", "type": "text"})) password1 =forms.CharField(widget=forms.TextInput({"placeholder": "Password", "class": "form-control", "type": "password"})) password2 =forms.CharField(widget=forms.TextInput({"placeholder": "Re-type Password", "class": "form-control", "type": "password"})) streetAddress = forms.CharField(widget=forms.TextInput({"placeholder": "Street Address", "class": "form-control", "type": "text"})) suburb = forms.CharField(widget=forms.TextInput({"placeholder": "Suburb", "class": "form-control", "type": "text"})) postcode = forms.CharField(widget=forms.TextInput({"placeholder": "Postcode", "class": "form-control", "type": "text"})) phoneNumber = forms.CharField(widget=forms.TextInput({"placeholder": "Phone Number", "class": "form-control", "type": "tel"})) website = forms.CharField(widget=forms.TextInput({"placeholder": "Website", "class": "form-control", "type": "url"})) class Meta: model= Employer fields= ('first_name', 'last_name','username' ,'email', 'streetAddress', 'suburb', 'postcode', 'phoneNumber', 'password1', 'password2' ) models.py class User(AbstractUser): class Role(models.TextChoices): ADMIN = 'ADMIN', … -
How to Integrate my Python with Django and HTML
Hi I'm extremely new to Django, like yesterday new. I was scouring the web for hours searching for a way to integrate a simple Python project I made to Django in order to keep me on track. I want to use Django as I'm going to be using Django in my classes soon and would like to learn. Is there any way I can do this? WANTS: I want to use Python for my backend & Django framework to link some HTML, CSS, and possible JavaScript to make thing look nice. Python Timer Project import time import os from threading import Thread def userTimeSet(): while True: try: hours = int(input("Number of hours? ")) minutes = int(input("\nNumber of minutes? ")) if hours > 0 and minutes > 0: interval_sec = (hours*3600)+(minutes*60) print(f"hours and minutes to seconds checking: {interval_sec}") elif hours > 0 and minutes == 0: interval_sec = (hours*3600) print(f"hours to seconds checking: {interval_sec}") elif hours == 0 and minutes > 0: interval_sec = (minutes*60) print(f"minutes to seconds checking: {interval_sec}") else: print("invalid.") futureTime = timeConfirmation(hours, minutes) # create and start the daemon thread print('Starting background task...') daemon = Thread(target=timeCheck, args=(futureTime, interval_sec,), daemon=True, name='Background') daemon.start() print('Main thread is carrying on...') time.sleep(interval_sec) print('Main … -
Django application slow due to multiple foreign keys
I'm having trouble displaying and modeling in django with multiple foreign keys. When displaying or creating it takes a long time as I have a lot of data. For example when trying to create with CreateView it takes a long time, or when trying to display the stored data. Is there any way to optimize the creation and at the time of display? The models with multiple foreging key and ManyToManyField are the following: class Player(models.Model): name = models.CharField("Nombre", max_length=100, blank=True, null=True) player = models.ForeignKey(Socio, on_delete=models.CASCADE, related_name="player_socio") division = models.ForeignKey(Division, on_delete=models.CASCADE,related_name="player_division", blank=True, null=True) goals = models.IntegerField("Goles", default=0) league = models.ForeignKey("League", on_delete=models.CASCADE, related_name="player_league") class Team(models.Model): team = models.CharField("Equipo", max_length=50, blank=True, null=True) league = models.ForeignKey("League", on_delete=models.CASCADE, related_name="team_league", blank=True, null=True) players = models.ManyToManyField(Player, blank=True, related_name="player_team") class Match(models.Model): league = models.ForeignKey(League, on_delete=models.CASCADE, related_name="match_league") date = models.DateField("Fecha", default=timezone.now) week = models.IntegerField("Semana", default=0) team_1 = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="team_1_goal") team_2 = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="team_2_goal") class Goal(models.Model): goal = models.IntegerField("Goles", default=0) match = models.ForeignKey(Match, on_delete=models.CASCADE, null=True, blank=True, related_name="match_goals") player = models.ForeignKey(Player, on_delete=models.CASCADE, null=True, blank=True, related_name="player_goal") league = models.ForeignKey("League", on_delete=models.CASCADE, related_name="player_league_goal") And when creating or displaying the data I use class-based views. I tried to display the data with select2 but it's still slow. Thank you in advance -
Multiple django instances on Apache Windows using the same virtual host
I have a WAMP Server 3.2 (Apache 2.4.46) installed on Windows 10 (64-bits), it is exposed to the local company network. I need to deploy several django projects under the same host - the company network doesn't allow another ServerName. Is it possible at all? Daemon Processing is not an option since this is Windows. My httpd-vhosts.conf: <VirtualHost *:80> ServerName XXXXXXXXXXXX DocumentRoot "d:/projects" WSGIPassAuthorization On WSGIScriptAlias /site1 "d:\projects\site1\site1\wsgi_windows.py" WSGIScriptAlias /site2 "d:\projects\site2\site2\wsgi_windows.py" WSGIApplicationGroup %{GLOBAL} <Directory "d:\projects\site1\site1"> <Files wsgi_windows.py> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Files> </Directory> <Directory "d:\projects\site2\site2"> <Files wsgi_windows.py> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Files> </Directory> Alias /static "d:/projects/site1/static" <Directory "d:/projects/site1/static"> Require all granted </Directory> </VirtualHost> Example of wsgi_windows.py for site1: activate_this = r'C:/Users/XXXXX/Envs/XXXXXX/Scripts/activate_this.py' exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site site.addsitedir(r'C:/Users/XXXXX/Envs/XXXXXX/Lib/site-packages') sys.path.append(r'D:/Projects/site1') sys.path.append(r'D:/Projects/site1/site1') os.environ['DJANGO_SETTINGS_MODULE'] = 'site1.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Right now I have Apache running only site1. If I try to reach site2 I got a error 404 "Page is not found" and Django error page listing the available urls for site1 (I have DEBUG=True). Is it possible to get both site1 and site2 working? -
How do I handle dependency injection in Django?
I am currently trying to manage dependency injection in a django application. I found this thread (Is this the right way to do dependency injection in Django?) and tried the following simple example based on what I found there. /dependencyInjection/serviceInjector.py from functools import wraps class ServiceInjector: def __init__(self): self.deps = {} def register(self, name=None): name = name def decorator(thing): """ thing here can be class or function or anything really """ if not name: if not hasattr(thing, "__name__"): raise Exception("no name") thing_name = thing.__name__ #Set the name of the dependency to the name of the class else: thing_name = name #Set the name of the dependency to a name specified in the register function self.deps[thing_name] = thing # I don't think we will be doing this //Elias return thing return decorator def inject(self, func): @wraps(func) def decorated(*args, **kwargs): new_args = args + (self.deps, ) return func(*new_args, **kwargs) return decorated init.py from backend.dependencyInjection.serviceInjector import ServiceInjector si = ServiceInjector() /core/articleModule.py from backend.core.IarticleModule import IarticleModule from models import Article from backend.__init__ import si @si.register() class articleModule(IarticleModule): def getArticleByLioId(self, lioId: str) -> Article: return Article.objects.get(lioId = lioId) /services/articleManagementService.py from backend.services.IarticleManagementService import IarticleManagementService from backend.models import Article from backend.__init__ import si @si.register() class articleManagementService(IarticleManagementService): @si.inject … -
@apollo/client useLazyQuery .then() triggers even when there's an error (React/graphene-django)
I have a graphene-django backend with a me query that returns an exception: You do not have permission to perform this action if the user is not logged in. From React I'm calling the query like this: const [getMe] = useLazyQuery(ME_QUERY); // query not important React.useEffect(() => { getMe() .then((meRes) => { console.log('Hit the .then()'); if (meRes.data && meRes.data.me) { setUser(meRes.data.me); } }) .catch(() => { console.log('Hit the .catch()'); }); }, []) The response I get from the backend: {"errors":[{"message":"You do not have permission to perform this action","locations":[{"line":2,"column":3}],"path":["me"]}],"data":{"me":null}} I would expect that @apollo/client would recognize this as an error and my console would output Hit the .catch(), but for some reason it's not hitting the catch at all and only outputs Hit the .then(). Why would that response resolve instead of reject in @apollo/client? I only have this issue with queries, not with mutations which work as expected. For instance if I call this mutation: const [createUser, { data, loading, error }] = useMutation(CREATE_USER_MUTATION); createUser({ variables: { email, password1, password2, }, }).then(() => { console.log('this should not be hit'); }); And I receive this response: {"errors":[{"message":"['This password is too short. It must contain at least 8 characters.', 'This password is … -
How to return a random number asynchronously using AJAX and Django
As a beginner I apologize to being not particular as you wish, but hopefully you'll understand my problem. What I am trying to achieve is simply returning a random value every 1.5 seconds without manually refreshing the browser. So far my code looks like this and it works, but I am convinced that my approach is kind of weird and around. Is there any possibilty to have just one function that actually does the same as these two or any cleaner way to achieve this? views.py: def generate_random(request): return render(request, "form.html") def generate_number(request): return HttpResponse(randint(0, 30)) my form.html is: <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> </head> <body onload="getRandomInt();"> <h2 id="result"></h2> <script> function getRandomInt() { setTimeout(function () { $.get("url", function(data, status){ $('#result').html(data); }); getRandomInt(); }, 1500) return false; } </script> </body> and urls.py: urlpatterns = [ path('',generate_random), path('url',generate_number), ] -
Use a related field in lookup_field in Django REST framework
I have a user model and a profile model that is created automatically when a user is registered. In my view for retrieving the user profile, I am trying to get the user profile using the username but DRF uses pk by default. So I added a lookup field with the username but DRF can't seem to resolve it: my profile model: class Profile(TimeStampedModel): user = models.OneToOneField('User', on_delete=models.CASCADE, related_name='customer_profile') bio = models.TextField(blank=True) image = models.URLField(blank=True) def __str__(self): return self.user.username my profile serializer: class ProfileSerializer(serializers.ModelSerializer): username = serializers.StringRelatedField(source='user.username', read_only=True) bio = serializers.CharField(allow_blank=True, allow_null=True) image = serializers.SerializerMethodField() class Meta: model = Profile fields = ['username', 'bio', 'image'] def get_image(self, obj): if obj.image: return obj.image return 'https://static.productionready.io/images/smiley-cyrus.jpg' my profile retrieving view: class ProfileRetrieveAPIView(generics.RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'username' def retrive(self, request, username, *args, **kwargs): try: profile = Profile.objects.select_related('user').get( user__username = username ) except Profile.DoesNotExist: ProfileDoesNotExist serializer = self.serializer_class(profile) return Response(serializer.data, status=status.HTTP_200_OK) my profile endpoint: urlpatterns = [ # .... path('profiles/<str:username>', views.ProfileRetrieveAPIView.as_view()), ] I am getting the error: Cannot resolve keyword 'username' into field. Choices are: bio, created_at, id, image, updated_at, user, user_id What am I doing wrong? -
Django debugger vs running From terminal
I'm trying to authenticate a basic django webapp with my firebase cloud db. So the problem is when i login normally providing the appropriate username and password, the login is sucessfull and i get redirected to the home page. But when i run a debugger i get an error saying : Internal Server Error: /login/ Traceback (most recent call last): File "c:\Users\moham\OneDrive\Desktop\Granular\web solution\web_solution\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "c:\Users\moham\OneDrive\Desktop\Granular\web solution\web_solution\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\moham\OneDrive\Desktop\Granular\web solution\Chosen_granular\apps\authentication\views.py", line 26, in login_view if (firebase_authentication(user.email,password)): AttributeError: 'NoneType' object has no attribute 'email' And this is how my login view function looks like. def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if (firebase_authentication(user.email,password)): #user = auth.get_user_by_email(user.email) #request['uid']=user.uid login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg": msg}) -
Why is it not showing me the permissions or the group on django?
enter image description here Why is it not showing me the permissions or the group on django? -
Annotate queryset models with fields from "through" model
This seems like it should be easy, but I've been unable to find an answer despite lots of googling. I have two models joined by a many-to-many relationship through a third model that has some additional fields. class User(AbstractUser): pass class Project(models.Model): name = models.CharField(max_length=100, unique=True, blank=False) description = models.CharField(max_length=255, blank=True) users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='projects', through='UserProject') # additional project fields class UserProject(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) favorite = models.BooleanField(default=False) last_used = models.DateTimeField(default=timezone.now) what I want is to be able to access a given user's projects along with the favorite and last_used fields for that user for each project. I cannot figure out how to do that using annotations or any other method on a call to user.projects. If I call the through relationship directly (i.e., user.userproject_set), I can add fields from the project with a single sql query by calling, e.g., user.userproject_set.select_related('project').annotate(name='project.name'), but then the models in the resulting queryset are UserProjects, not Projects, which is not what I want. Writing a sql query to do what I want would be trivial (it would basically be the same query Django produces to join the Project fields to the UserProject queryset). Is there a way to get … -
nginx, uwsgi, django. uwsgi runs fine as normal user, fails when started by root, even with su -u nonroot
I am trying to get nginx, Django, and uwsgi to work 'as specified' in the docs (well, ok, https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html anyway). Everything works perfectly as long as I start uwsgi as NON-root user. In trying to get past this, I created a little script (the commented-out commands are things I've tested, sorry if they are confusing): #!/bin/bash cd /home/lunchspace/FridayLunch/ uwsgi --ini lunchspace_uswgi.ini #uwsgi --socket /home/lunchspace/lunchspace.sock --module FridayLunches.wsgi #uwsgi --emperor /etc/uwsgi/vassals Running the above as the user 'lunchspace', I get: lunchspace@lunchspace:~/FridayLunch$ ../runuwsgi [uWSGI] getting INI configuration from lunchspace_uswgi.ini *** Starting uWSGI 2.0.20 (64bit) on [Fri Sep 23 19:29:55 2022] *** compiled with version: 7.5.0 on 13 September 2022 22:35:31 os: Linux-4.15.0 #1 SMP Tue Jan 25 12:49:12 MSK 2022 nodename: lunchspace.org machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/lunchspace/FridayLunch detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/lunchspace/FridayLunch your processes number limit is 62987 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to UNIX address /home/lunchspace/FridayLunch/lunchspace.sock fd 3 Python version: 3.6.9 (default, Jun 29 … -
How to make multiple urls in django?
Learning django, can't create multithreaded url How to display, for example, the brand of an audi car by url 127.0.0.1:8000/cars_brand/audi/Audi_TTS ? Now it says None I don't know what else to add here, but stackoverflow doesn't skip my question for the reason: It looks like your post is mostly code; please add some more details. views from django.shortcuts import render from django.http import HttpResponse # Create your views here. cars_brand_dict = { "audi": ["Audi_RS_2_Avant", "Audi_A8_W12", "Audi_TTS"], "bmw": ["BMW_M135i_xDrive", "BMW_M240i_xDrive_Coupe", "BMW_M3_Competition"], "volkswagen": ["Volkswagen_Caddy","Volkswagen_Multivan","Volkswagen_Crafter_Pritsche"], } cars_model_dict = { "audi_dict" :{ "Audi_RS_2_Avant": "ссылочка Audi_RS_2_Avant", "Audi_A8_W12": "ссылочка на Audi_A8_W12", "Audi_TTS": "ссылочка на Audi_TTS", }, "bmw_dict" :{ "BMW_M135i_xDrive": "ссылочка на BMW_M135i_xDrive", "BMW_M240i_xDrive_Coupe": "ссылочка на BMW_M240i_xDrive_Coupe", "BMW_M3_Competition": "ссылочка на BMW_M3_Competition", }, "volkswagen_dict" :{ "Volkswagen_Caddy": "ссылочка на Volkswagen_Caddy", "Volkswagen_Multivan": "ссылочка на Volkswagen_Multivan", "Volkswagen_Crafter_Pritsche": "ссылочка на Volkswagen_Crafter_Pritsche", } } def get_info_about_car_brand(request, car_brand): description = cars_brand_dict.get(car_brand, None) return HttpResponse(description) def get_info_about_car_model(request, car_brand, car_model): description = cars_model_dict.get(car_model) return HttpResponse(description) default urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('cars_brand/', include("car_store.urls")), ] my urls from django.urls import path from . import views urlpatterns = [ # path('', admin.site.urls), path('<car_brand>', views.get_info_about_car_brand), path('<car_brand>/<car_model>', views.get_info_about_car_model), ] -
linking JavaScript code to Django database upon clicking on a button
I'm asked to work on a networking website that is like Twitter. I work with HTML,CSS, Javascript for the client-side and Django for the server-side. I'm trying to link between Javascript and Django using JSON and fetch as I want to create a button in each of the users' profile that upon being clicked by the registered user, it makes the registered follow the profile as it is saved in django database as a model containing the follower(follower) and the user followed(following) but upon clicking on follow button (in user.html) it doesn't save any data in the database in models.py: class follow(models.Model): follower = models.ForeignKey("User",on_delete=models.CASCADE, related_name="follower") following = models.ForeignKey("User",on_delete=models.CASCADE, related_name="following") in user.html(contains the script): <html> <head> <script> document.addEventListener('DOMContentLoaded',function(){ document.querySelectorAll('input').forEach(input =>{ input.addEventListener('click', function(){ console.log(input.id); let follow_username = input.id fetch('/follow/'+ follow_id, { method:'PUT', body: JSON.stringify({ follow: true }) }) }) } ) }); </script> </head> <body> <h2>{{x.username}}</h2> <form> {% csrf_token %} <input type="submit" value="follow" name ="follow" id={{x.username}}> </form> </body> </html> in urls.py: from django.urls import path from . import views urlpatterns = [ path("follow/<str:name>", views.Users, name="follow") ] in views.py: def Users(request, name): x = User.objects.get(username = name) if request.method == 'PUT': data = json.loads(request.body) if data.get('follow') is not None: user = request.user … -
Are user provided translations for user provided templates possible with the django template engine?
In my webapp, I'd like to allow users who want to deploy an instance to write their own templates. Specifically, I would like to include a template for a data protection declaration using the include tag and have this point to a location which users can define in their settings. However, this would not be translatable, as all translated strings have to be in django.po and that file is in version control. Is there a way to extend django.po, e.g. use an include statement to point it to a second, user generated translations file, similar to how I can include templates within other templates? -
Importing python file to views and dynamic url
I have a particular function established in a task.py file. I want to create a views file in django which imports task.py file,calls the function,links it to dynamic url and displays output using HttpResponse. I have tried but my server just doesn't run. I'm a beginner. -
Django setting up view to change settings.py one-off settings
I'm nearly done with my Django app and I was wondering if it's to create a custom page where the app user admin will be able to cahnge one-off overall app settings like language, timezone, currency, URL slug, app limits (e.g. Max number of xyz, default abc etc) etc Is this possible? Feel like I'm missing a trick here. Any advice or resoucrces would be great.