Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Model instance with entries from another model
I need to create a website that allows the administrator to compose a catalogue of project parameters (with categories, subcategories and values). The users should then use this catalogue as a template to fill in their values. So I created a ParameterCatalogue model with a OneToOneField to the Project model. class ParameterCatalogue(models.Model): project = models.OneToOneField(Project, on_delete=models.CASCADE, related_name='catalogue') An abstract Parameter class with common attributes and methods: class Parameter(models.Model): class Meta: abstract = True class Category(models.IntegerChoices): pass parameter_catalogue = models.project(Parameter, on_delete=models.CASCADE) name = str category = models.CharField(max_length=16, blank=True) subcategory = models.CharField(max_length=16, blank=True, default="") value = models.DecimalField(name="value", decimal_places=1, max_digits=6) and a few Parameter classes that inherit from it: class ParameterA(Parameter): name = 'parameter_a' class Category(models.TextChoices): CAT_1 = 1, _('CAT1') CAT_2 = 2, _('CAT2') CAT_3 = 3, _('CAT3') CAT_4 = 4, _('CAT4') category = models.CharField(max_length=4, choices=Category.choices, default=Category.CAT_1) class ParameterB(Parameter): name = 'parameter_b' class Category(models.IntegerChoices): CAT_1 = 1, _('CAT1') CAT_2 = 2, _('CAT2') CAT_3 = 3, _('CAT3') CAT_4 = 4, _('CAT4') CAT_5 = 5, _('CAT5') CAT_6 = 6, _('CAT6') CAT_7 = 7, _('CAT7') category = models.PositiveSmallIntegerField(choices=Category.choices) Now I want to create a Model that resembles ParameterCatalogue for the user values. I want the instances of this model to mirror the ParameterCatalogue instance of the … -
insert extra dynamic input fields into database
I am trying to add all the values of a dynamic input field into the database using the logic below. The model that has the dynamic field is declared like this: class MyModel(models.Model): # some_field dynamic_field = models.CharField("List of URLs", max_length=255, blank=True) # other_field The view I'm using to process the form looks like this: model_instance = MyModel.objects.get(pk_id=pk_id) model_form = MyModelForm(instance=model_instance) if request.method == 'POST': submitted_form = MyModelForm(request.POST) if submitted_form.is_valid() MyModelForm(request.POST, instance=model_instance).save() When the model is rendered in the browser, it looks like this: <input type="text" name="dynamic_field" value="url1" maxlength="255" id="id_dynamic_field"> Using JS, I am appending extra text inputs to the form, with the same name as dynamic_field When I print out request.POST in the view, I see all the values of dynamic_field in a list as (assuming url2 is the value for a dynamic input field added to the form) <QueryDict: {'csrfmiddlewaretoken': ['....'], 'dynamic_field': ['url1', 'url2'], 'some_field': [''], 'other _fields': ['']}> Only url2 is inserted into the database....essentially the last value. How can I insert both url1 and url2 into the database? -
Is it possible to add CK Editor in django admin without installing `django-ckeditor`?
I have a blogging website and when I upload it to pythonanywhere.com using free hosting it doesnot allow me to install the django-ckeditor module. Please answer if there is any solutution for that or is there any way to use it without installing django-ckeditor? -
Django UNIQUE constraint failed: players_comment.user_id
I'm trying to post comment but it's not getting posted, rather this error is appearing UNIQUE constraint failed: players_comment.user_id. I don't know why this error is occuring. Can anyone help me out of this? Thanks in advandce! My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body', 'transfernews') My models.py : class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My views.py: def transfer_targets(request): transfernews = Transfernews.objects.all() form = CommentForm(request.POST or None) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user new_comment.save() return redirect('transfernews/') return render(request, 'transfernews.html', {'transfernews': transfernews, 'form': form}) My transfernews.html: {% for transfer in transfernews %} {% if not transfer.comments.all %} No comments Yet... {% else %} {% for comment in transfer.comments.all %} <strong> {{ comment.user.username }} - {{ comment.date_added }} </strong> <br/> {{ comment.body }} <br/><br/> {% endfor %} {% endif %} <hr> <div>Comment and let us know your thoughts</div> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button> <button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button> </form> {% … -
Redis-server cache auto clearing
I was using Django with celery and redis-server. The redis server is Auto clearing all the cache data after I deployed the Wordpress site on the same AWS instance. I am not getting the root cause of the issue. Below is the Key Space notifications I got on the redis console. "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@0__:backup4","set" "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@0__:backup3","set" "pmessage","__key*__:*","__keyevent@0__:set","backup3" "pmessage","__key*__:*","__keyspace@0__:backup3","set" "pmessage","__key*__:*","__keyevent@0__:set","backup3" "pmessage","__key*__:*","__keyspace@0__:backup4","set" "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@0__:backup4","set" "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@0__:backup3","set" "pmessage","__key*__:*","__keyevent@0__:set","backup3" "pmessage","__key*__:*","__keyspace@0__:backup4","set" "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@1__:unacked_mutex","set" "pmessage","__key*__:*","__keyevent@1__:set","unacked_mutex" "pmessage","__key*__:*","__keyspace@1__:unacked_mutex","expire" "pmessage","__key*__:*","__keyevent@1__:expire","unacked_mutex" "pmessage","__key*__:*","__keyspace@1__:_kombu.binding.celery","sadd" "pmessage","__key*__:*","__keyevent@1__:sadd","_kombu.binding.celery" "pmessage","__key*__:*","__keyspace@1__:celery","lpush" "pmessage","__key*__:*","__keyevent@1__:lpush","celery" "pmessage","__key*__:*","__keyspace@1__:unacked_index","zadd" "pmessage","__key*__:*","__keyevent@1__:zadd","unacked_index" "pmessage","__key*__:*","__keyspace@1__:unacked","hset" "pmessage","__key*__:*","__keyevent@1__:hset","unacked" "pmessage","__key*__:*","__keyspace@1__:unacked_index","zrem" "pmessage","__key*__:*","__keyevent@1__:zrem","unacked_index" "pmessage","__key*__:*","__keyspace@1__:unacked_index","del" "pmessage","__key*__:*","__keyevent@1__:del","unacked_index" "pmessage","__key*__:*","__keyspace@1__:unacked","hdel" "pmessage","__key*__:*","__keyevent@1__:hdel","unacked" "pmessage","__key*__:*","__keyspace@1__:unacked","del" "pmessage","__key*__:*","__keyevent@1__:del","unacked" "pmessage","__key*__:*","__keyspace@1__:celery","lpush" "pmessage","__key*__:*","__keyevent@1__:lpush","celery" -
How does code splitting actually work? (and how can I code split with django?)
I'm using Django to serve HTML files, with a react application inside one of them. The application is too large and I would like to implement code splitting. This is simple enough to do with webpack, which I get allows me to break up the application into smaller files. I can load the scripts in order in the HTML template, but doesn't this just mean they'll all be loaded one at a time HTML page is served? How does webpack's code splitting actually determine which files are requested from the server, only at the points at which they're required by the user? Also, does anyone know how to correctly React code splitting in this way with Django? -
Traefik headers hostsProxyHeaders meaning
What does Traefik's Headers hostProxyHeaders configuration do? I am looking at traefik.yml settings from django-cookiecutter (link) middlewares: csrf: # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax headers: hostsProxyHeaders: ["X-CSRFToken"] I understand that it is required for CSRF header which django uses. Why is this configuration required and what happens if this configuration is not set? -
Django url namespace:app_name:url_name problem
When I look at the documentation of django, it says that I can redirect like this, but it doesn't work. urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls' , namespace='store')), path('yedek', include('store.urls' , namespace='store-yedek')), ] app_name = 'store' urlpatterns = [ path('', views.all_products, name='all_products'), path('item/<slug:slug>/', views.product_detail, name='product_detail'), path('search/<slug:category_slug>/', views.category_list, name='category_list'), ] -
cmd prompt and vscode showing different versions of django for same environment
I use command py -m django --version in cmd prompt it returns 3.2 as my django version but when i use the same command in vscode it returns 3.1.9. Can anybody explain why -
List all attributes in a model (Django)
I'm working on a blog app and I'm trying to get all posts to be listed on the index/homepage. Here's my BlogPost model: from django.db import models # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title return f"{self.text[:50]}..." My views.py: from django.shortcuts import render from .models import BlogPost # Create your views here. def index(request): posts = BlogPost.objects.order_by('-date_added') body = BlogPost.objects.values('text') context = {'posts': posts, 'body':body} return render(request, 'blogs/index.html', context) and my index.html: <p> Blog </p> <p> Here's some articles I've written: </p> {% for post in posts %} <h1> {{post}} </h1> <p> {{body}} </p> {%empty%} <li> Sacrebleu! Where is me posts? </li> {%endfor%} The issue is how it's being displayed: Blog Here's some articles I've written: Favorite things: <QuerySet [{'text': "blah blah blah"}, {'text': "lorem ipsum"}]> This is a test: <QuerySet [{'text': "blah blah blah"}, {'text': "lorem ipsum"}]> Instead, I'd like for it to display as: Blog Here's some articles I've written: Favorite things: blah blah blah This is a test: lorem ipsum I feel like it has something to do with the id attribute, but I really can't point it out. -
Test a view function with a HTTP404 exception
I'm trying to test this view to ensure that it returns a HTTP404 if the RedirectUrl model class does not exist and redirect to the destination_url if it does. Also it should store the url. #Views.py def clickActivity(request: HttpRequest, pk: int, whatsappid: int) -> HttpResponse: try: redirect_url = RedirectUrl.objects.get(id=pk) except RedirectUrl.DoesNotExist: raise Http404("No RedirectUrl matches the given query.") store_url_entry = RedirectUrlsEntry(url=redirect_url) store_url_entry.save() destination_url = f"{redirect_url.symptom_check_url}" f"/?whatsappid={whatsappid}" return HttpResponseRedirect(destination_url) #models.py class RedirectUrl(models.Model): url = models.URLField( max_length=255, blank=True, null=True, default="https://hub.momconnect.za/confirmredirect", ) content = models.TextField( default="This entry has no copy", help_text="The content of the mesage that this link was sent in", ) symptom_check_url = models.URLField( max_length=200, null=False, blank=False, default="http://symptomcheck.co.za" ) parameter = models.IntegerField(null=True, blank=True) time_stamp = models.DateTimeField(auto_now=True) def my_counter(self): total_number = RedirectUrlsEntry.objects.filter(url=self.id).count() return total_number def __str__(self): if self.url: return ( f"{self.parameter}: {self.url}/{self.id} \n" f"| Clicked {self.my_counter()} times | Content: {self.content}" ) class RedirectUrlsEntry(models.Model): url = models.ForeignKey( RedirectUrl, on_delete=models.CASCADE, blank=True, null=True ) time_stamp = models.DateTimeField(auto_now=True) def __str__(self): if self.url: return ( f"{self.url.url} with ID {self.url.id} \n" f"was visited at {self.time_stamp}" ) #Urls.py urlpatterns = [ path( "confirmredirect/<int:pk>/<int:whatsappid>", views.clickActivity, name="ada_hook_redirect", ), path("redirect/<int:pk>", views.default_page, name="ada_hook"), ] I was able to test that the right templates are used but I'm struggling with this test. I'm a Django … -
How to get a json response object from backend side to frontend with django?
I tried to send a json object from django views to django template but that is going as a string instead of json object. This object(json_follower) is sending from view to django template which i'm consoling as shown you the output with an image screenshot. class UserProfileFollowToggle(LoginRequiredMixin,View): login_url = '/accounts/login/' def post(self, request): username_to_toggle = request.POST.get("user_toggle") json_follower = None profile_, is_following,json_follower = UserProfile.objects.toggle_follow(request.user, request.user.id ,username_to_toggle,json_follower) return JsonResponse({'result': is_following, 'json_follower':json_follower}) And inside view, I'm inheriting that json_follower from model manager as you can see in the given below code. def some_view(username_to_toggle): print(username_to_toggle,"User to togle") user = User.objects.get(username__iexact=username_to_toggle) print(user,"User object") user_seri = serializers.serialize('json', [user]) user_json = json.dumps(user_seri) print(user_json,"User json") return user_json class ProfileManager(models.Manager): def toggle_follow(self, request_user,user_id, username_to_toggle,json_follower): profile_ = UserProfile.objects.get(user__username__iexact=request_user.username) is_following = False follower = profile_.follower.filter(username__iexact=username_to_toggle).first() if follower: profile_.follower.remove(follower.id) actor = User.objects.get(pk=user_id) user = User.objects.get(username=username_to_toggle) json_follower = some_view(username_to_toggle) #this someview function is written on the top of this model. else: new_follower = User.objects.get(username__iexact=username_to_toggle) profile_.follower.add(new_follower.id) actor = User.objects.get(pk=user_id) user = User.objects.get(username=username_to_toggle) notify.send(actor, recipient=user, verb='follow you') json_follower = some_view(username_to_toggle) #this someview function is written on the top of this model. is_following = True return profile_, is_following,json_follower -
Simple app from Github - Can't connect to localhost
https://github.com/faisalshahbaz/django-calculator Hi there. I'm a total beginner and I just need to run this app, but have no idea how to do it. Python, pip, django etc. all are installed. I cloned the app with Git. Created a virtualenv. Open the project with Vscode (Python extension installed as well), open the cmd and typed manage.py runserver but got this error: C:\Users\Hp\Desktop\django-calculator>python manage.py runserver python: can't open file 'C:\Users\Hp\Desktop\django-calculator\manage.py': [Errno 2] No such file or directory -
Connecting Django to SQL Server
I am trying to connect my Django 3.0.7 project with SQL Server 17, in docker containers. here is my settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db_name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'mysql', 'PORT': '3306', 'OPTIONS': { 'provider': 'MSOLEDBSQL', 'driver': 'ODBC Driver 17 for SQL Server', }, }, } And this is the mysql service in docker-compose.yml mysql: image: mysql/mysql-server:8.0 restart: unless-stopped environment: - MYSQL_ROOT_PASSWORD=rootpassword - MYSQL_USER=user - MYSQL_PASSWORD=password - MYSQL_DATABASE=db_name ports: - 3306:3306 volumes: - mysql:/var/lib/mysql after the docker-compose up -d and all containers are started, I get the following: ('HY000', '[HY000] [Microsoft][ODBC Driver 17 for SQL Server]Protocol error in TDS stream (0) (SQLDriverConnect)') -
Extract a common field from JSON results on Django
I'm currently developing a parking place reservation app, and I have an admin-only feature where I can see how many reservations are in an interval. At the moment, my JSON is the following: "count": 8, "next": null, "previous": null, "results": [ { "city": "city_name", "interval": { "init_date": "2021-03-02T00:00:00Z", "end_date": "2021-03-17T00:00:00Z", "label": "02-03-2021" }, As you can see, I have 8 intervals with the same information, the two dates, the label, the amount of reservations, and the city. The field city is the same for all the intervals, and I want to extract that and show it only once. Is it possible to do that? My model is: class ReservationView(APIView, LimitOffsetPagination): """Basic APIView with pagination""" permission_classes = ( IsAuthenticated, IsDashboardUser, ) def get(self, request, *args, **kwargs): instance = self.paginate_queryset(self.get_interval_data(), request) serializer = ReservationSerializer( instance, context=self.get_serializer_context(), many=True, ) results = serializer.data return self.get_paginated_response(results) And my serializer is: class ReservationSerializer(serializers.Serializer, ReservationsMixin): city = serializers.SerializerMethodField("_get_city") interval = serializers.SerializerMethodField("_get_datetime") metrics = serializers.SerializerMethodField("_get_metrics") I tried to do to_representation() but it only adds the city name to the end of every interval. -
Django graphene subscriptions keep loading without sending me the data
I followed the instrections here with an existed graphen api gitHub repo. Hoever, I tried all the three options graphql-python/graphql-ws datavance/django-channels-graphql-ws jaydenwindle/graphene-subscriptions. but non of them worked with me. problem: enter image description here as you can see here it is loading forever without sending the data. goal : I need to create realtime grapheql api (subscriptions) files: Note: in the repo you will see the original repo without the subscriptions code. -
Django view is not creating records in Database
i am not able to create record in a table FinTransDetail by admin: when I trying to add records I am getting errors. Please help to solve the issues. As I could not add by admin I can not add records by my View as well. But I can add record in FinTransHeader both by admin and by me view. Model: class FinTransHeader(models.Model): """Model representing a book (but not a specific copy of a book).""" fh_type = models.CharField(max_length=200) fh_code = models.CharField(max_length=200) fh_no = models.DecimalField(max_digits = 5, decimal_places = 0,unique=True) fh_dt = models.DateField() fh_detail=models.CharField(max_length=200,blank=True,null=True) fh_cust_code = models.CharField(max_length=200,blank=True,null=True) fh_user_code =models.CharField(max_length=200,blank=True,null=True) fh_ref=models.CharField(max_length=200,default='nil',blank=True,null=True) fh_status=models.CharField(max_length=1,default=0) fh_post_status = models.BooleanField(default=False) th_prt_status=models.BooleanField(default=False) def __str__(self): """String for representing the Model object.""" return str(self.fh_code) # return self.fh_no class FinTransDetail(models.Model): fd_no = models.ForeignKey( FinTransHeader,on_delete=models.CASCADE) fd_acct = models.ForeignKey(AccountMaster, to_field='AcctCode',on_delete=models.CASCADE) fd_debit = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_credit = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_detail=models.CharField(max_length=200, null=True, blank=True ) fd_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_posting=models.BooleanField(default=False, blank=True, null=True) def __str__(self): """String for representing the Model object.""" # return self.ToString(AcctCode)+"-"+self.AcctName return str(self.fd_no) when I am trying to add records in FinTransDetail i am getting Html error as below: TypeError at /admin/waccounts/fintransdetail/add/ __str__ returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/admin/waccounts/fintransdetail/add/ Django Version: 3.1.1 Exception Type: … -
How to add a form in an html page in django
I want to add comments form a specific html which has it's own views and models and I do not want to create a new html file like comment.html which will only display the form and its views. I want users to be able to comment right underneath a post, so that users don't have to click a button such as "add comment" which will take them to a new page with the "comment.form" and then they can comment. Basically want a page with all transfer news and their respective comments as well as a comment-form under the old comment. But I'm stuck. I can add comments manually from the admin page and it's working fine, but it seems that I have to create another url and html file to display the comment form and for users to be able to add comments(btw I'm trying to build a sports related website). Thanks in advance! My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py : class … -
django.core.exceptions.FieldError: Unknown field(s) (foo) specified for MyModel
Documenting my own mistake. Hope this could help others ! models.py class MyModel(models.Model): foo = models.CharField(max_length=50), bar = models.IntegerField() forms.py class MyModelForm(forms.ModelForm): class Meta: fields = ['foo', 'bar'] Error during system check: django.core.exceptions.FieldError: Unknown field(s) (foo) specified for MyModel Whereas the field foo is defined on MyModel... -
attempted relative import with no known parent package django
There are two models and a signal and I want to implement the AutoUpdateBio section but when I run the code I face the bellow error models from django.contrib.auth.models import User from django.db import models class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) nickname = models.CharField(blank=True, null=True, max_length=50) location = models.CharField(blank=True, null=True, max_length=50) weight = models.DecimalField(null=True, max_digits=5, decimal_places=2) signals from .models import * from django.dispatch import receiver from django.db.models.signals import post_save, m2m_changed @receiver(post_save, sender=User, dispatch_uid='') def receiver_func(sender, instance, created, update_fields, **kwargs): if created and update_fields == None: profile = Profile.objects.create(user=instance) @receiver(m2m_changed, sender=Website.users.through) def AutoUpdateBio(sender, instance, action, reverse, pk_set, **kwargs): if action == 'post_add': # ** Add user to website - instance: website if not reverse: print(instance) print(pk_set) # ** Add website to user - instance: user else: print(instance) print(pk_set) I got this error when I run the code to see the print outputs traceback Traceback (most recent call last): File "d:..\accounts\signals.py", line 1, in <module> from .models import * ImportError: attempted relative import with no known parent package -
Django FileResponse don't download HTML file
I'm trying to download an pre-generated HTML file, but all that i've tried doesn't work. Searching StackOverflow i found that return FileResponse(open(file_path, 'rb')) will download a file, but intead of download, the HTML just is rendered on the tab. I think the problem is the browser receive the HTML and instead of display the "Save as" dialog just render it to the current tab. In my main template i have a form with target="_blank" tag, and a submit button that open (without AJAX) a new tab who suposed to download automatically the file. What i want: After i submit the code a new tab appears, the view related to that URL do some code (not related to the download) and after that process (that is working fine) download an HTML file to the device. The HTML exists and don't have any problem, te only problem it's that i want to DOWNLOAD the file but the browser display it instead. Note 1: Yes, i know that with right clic -> download i can download the HTML that i see, but this system is for non IT people, i need to do it the easest way possible. Note 2: I put the … -
DRF identify user by Bearer Token
I'm using Django-restframework with django-oauth-toolkit. My model has a foreign key to my custom user model class DiseaseCase(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name='daard_case_user', on_delete=models.CASCADE) My drf view: class DiseaseCaseViewset(viewsets.ModelViewSet): serializer_class = DiseaseCaseSerializer queryset = DiseaseCase.objects.all() http_method_names = ['get', 'post', 'head'] permission_classes = [IsAuthenticatedOrReadOnly] and my serializer: class DiseaseCaseSerializer(serializers.ModelSerializer): owner = serializers.SerializerMethodField('get_owner') # not working def get_owner(self, obj): from oauth2_provider.models import AccessToken tok_user = AccessToken.objects.get(token="GSY4QwID3NShVz7PoeeHSzsOg4naR9") return tok_user.user class Meta: model = DiseaseCase search_fields = ['name'] exclude = ['is_approved',] filter_backends = (filters.DjangoFilterBackend) As you see, I'm trying to identify the user based on the bearer token (as auth type) in get_ownerbut this fails asrequest` is empty in my serializer. NameError: name 'request' is not defined It feels like I'm reinventing the wheel or do not see the forest because of trees. How can I update the user field of my model based on token auth? -
'str' object has no attribute 'isComplete' when I try to reach foreign key attribute in DRF
First of all, I am new in DRF. I've searched about the error but I don't get where there is a str attribute. As far as I understand, it gets order and product in OrderItemViewSet as strings, but they are referring to other classes with a foreign key. This is my views.py class OrderItemViewSet(viewsets.ModelViewSet): queryset = OrderItem.objects.all() serializer_class = OrderItemSerializer detail_serializer_class = OrderItemDetailSerializer filter_backends = (DjangoFilterBackend, OrderingFilter, ) ordering_fields = '__all__' def get_serializer_class(self): if self.action == 'retrieve': if hasattr(self, 'detail_serializer_class'): return self.detail_serializer_class return super().get_serializer_class() def get_queryset(self): queryset = OrderItem.objects.all() product = self.request.query_params.get('product', None) order = self.request.query_params.get('order', None) if product is not None: product = product.album_name() queryset = queryset.filter(product__album_name=product) if order is not None: order = order.isComplete() queryset = queryset.filter(order__isComplete = order) return queryset def create(self, request): #parse incoming request or add new order item message = request.data.pop('event') if message == "NewOrderItem": event = request.data.pop('event') product = event.pop('product') orders = event.pop('orders')[0] #only one order customer = orders.pop('order') #not sure about selections product = Product.objects.create(**product) orders = Order.objects.create(**orders, product=product) #not sure orders.customer.create(**user) order = Order.objects.create(**event, product=product, order=orders) return Response(status=status.HTTP_201_CREATED) models.py class Product(models.Model): model_no = models.CharField(max_length=200, blank=True, null=True) album_name = models.CharField(max_length=200, blank=True, null=True) artist_name = models.CharField(max_length=200, blank=True, null=True) description = models.CharField(max_length=200, blank=True, null=True) … -
Creating a request to the django model
I have a model class paidparking(models.Model): adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True, verbose_name='Адрес парковки') carnumber = models.CharField(max_length=150,verbose_name='Номер автомобиля') amountoftime = models.IntegerField(verbose_name='Количество времени') price = models.FloatField(verbose_name='Цена') telephone = models.CharField(max_length=20,verbose_name='Номер телефона') email = models.EmailField(verbose_name='Электронный адрес',null=True,blank=True ) datetimepaidparking = models.DateTimeField(auto_now_add=True, verbose_name='Дата и время оплаты') expirationdate = models.DateField(null=True,verbose_name='Дата начала срока действия') expirationtime = models.TimeField(null=True,verbose_name='Время начала срока действия') enddateandtime = models.DateTimeField(null=True,blank=True,verbose_name='Окончание срока действия') The form has 2 fields with date selection In the function, I get the value from these fields startdate = datetime.strptime(request.POST['startdate'], '%d.%m.%Y') enddate = datetime.strptime(request.POST['enddate'], '%d.%m.%Y') In the model, the expirationdate field. The date in this field is in the format %d.%m.%Y I need to form a request to the django model. If the date in the expirationdate field falls between startdate and enddate, then all records must be retrieved -
Cannot connect Django to existing MySQL database (Symbol not found: _mysql_affected_rows)
So, I am having trouble connecting Django to an existing MySQL database (created from a dump for dev purposes). Here is my steps and all the terminal output: Get database ready Install MySql 5.7 Start MySQL brew services start mysql@5.7 Open MySQL Workbench and connect via password Create new schema Open MySQL Database dump; insert use climate at the top of file, run script -> Database is ready Setting up Django create new python venv python3 -m venv good-env Activate venv source good-env/bin/activate Installing django python -m pip install Django Downloading Django-3.2.2-py3-none-any.whl (7.9 MB) |████████████████████████████████| 7.9 MB 3.8 MB/s Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting asgiref<4,>=3.3.2 Using cached asgiref-3.3.4-py3-none-any.whl (22 kB) Collecting pytz Using cached pytz-2021.1-py2.py3-none-any.whl (510 kB) Installing collected packages: sqlparse, asgiref, pytz, Django Successfully installed Django-3.2.2 asgiref-3.3.4 pytz-2021.1 sqlparse-0.4.1 WARNING: You are using pip version 20.1.1; however, version 21.1.1 is available. You should consider upgrading via the '/Users/aaronkurz/Dev/2/good-env/bin/python -m pip install --upgrade pip' command. Creating a project django-admin startproject climatevisual; cd climatevisual Connecting Django with the database Installing required drivers (I know only mysqlclient should suffice, but that led to the same result so I started trying to install both...) pip install mysqlclient Installing collected packages: …