Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to upload 'django-rest-api server', and 'crawling.py'
Hi, guys. i have a problem. i made an android application written by kotlin. this app communicates to 'django-restapi server' to get some data. 'django-restapi server' gets data from 'crawling.py' file(using selenium,headless chrome). app : show data to people django-restapi server : get data from crawling.py, and saving data on database crawling.py(with chromedriver) : crawling data from website, and sending data to server so, what i want to know is, i don't know how to upload them. i want to use aws. what i'm thinking now is, upload 'django-restapi server' and 'crawling.py' to aws lambda seperately. then, i will run 2 lambda. but i think it's bad architecture. can you advice me better answer? -
"cleaned_data" isn't working as my browser shows back - " Exception Value: 'FormName' object has no attribute 'cleaned_data' "
and here is my VIEWS.PY, def form_view(request): form = forms.FormName() if request.method == 'POST': form = forms.FormName(request.POST) if form.is_valid: print("VALIDATION SUCCESS !!") d = form.cleaned_data['name'] print("name:", d) return render(request, 'baleno/form_pg.html', {'form': form}) -
how to complete my django app in the backend
I created a django app , I also set templates and static files . I made migrations my questions is : I want to scrape data from different websites and save it in django to be displayed in my templates what would be the next steps then ? -
I want to know,how does 'category' knows which model to access
template code- <a class="dropdown-item" href="{% url 'home' %}">All Products</a> {% for category in links %} <a class="dropdown-item" href="{{category.get_url}}">{{category}}</a> {% endfor %} context_processor.py def menu_links(request): links=Category.objects.all() return dict(links=links) Category Model- class Category (models.Model): name=models.CharField(max_length=250, unique=True) slug=models.SlugField(max_length=250, unique=True) description=models.TextField(blank=True) image=models.ImageField(upload_to='category',blank=True) def get_url(self): return reverse('products_by_category',args=[self.slug]) def __str__(self): return self.name Product model- class Product(models.Model): name=models.CharField(max_length=250, unique=True) slug=models.SlugField(max_length=250, unique=True) description=models.TextField(blank=True) category=models.ForeignKey(Category, on_delete=models.CASCADE) price=models.DecimalField(max_digits=10,decimal_places=2) image=models.ImageField(upload_to='product',blank=True) stock=models.IntegerField() available=models.BooleanField(default=True) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def get_url(self): return reverse('product_detail',args=[self.category.slug,self.slug]) def __str__ (self): return self.name here, as you can see the def get_url(self) is in Category as well as Product model I just want to know how come category in {{category.get_url}} knows to access the method in Category and not in Product model -
Reuse existing Django rest framework serializer
I am currently using Django Rest Framework and I am looking for a way to reuse some attributes from an already defined Serializer. In order to explain, I am going to expose some of the serializers involved: Completed Serializer: class ProductSerializer(serializers.ModelSerializer): subscribed = serializers.SerializerMethodField() other_field = serializers.SerializerMethodField() class Meta: model = Product fields = [ 'id', 'name', 'subscribed', 'other_field', 'x', 'y', 'z' ] def get_subscribed(self, product: Product): return product.is_user_subscribed(self.context['request'].user) Simplified Serializer: class ProductSimplifiedSerializer(serializers.ModelSerializer): subscribed = serializers.SerializerMethodField() class Meta: model = Product fields = [ 'id', 'name', 'subscribed' ] def get_subscribed(self, product: Product): return product.is_user_subscribed(self.context['request'].user) As you can notice above, those serializers are almost the same, but one of them is a simplified version of the object because I don't want to retrieve unnecessary information in some parts. The problem here is that in this scenario we have a method serializer that will need to be maintained two times. Maybe in the future, I would want to add another field, and I will need to add it to both. So, how could be achieved a Based Serializer in which all the fields are included but I could reuse it and extract specific fields from it? I have already thought these options: … -
Django returns error but dosen't check for more Integrity errors afterwards
So a request that violates the check for postive_integer (e.g. positive_integer = -1), django will not check for errors against unique_together (e.g. record with same name and user already exist) and will only return the original error from the positive_integer. class Foo(models.Model): positive_integer = models.PositiveIntegerField() name = models.CharField(max_length=100) user = models.CharField(max_length=100) class Meta: unique_together = (('name', 'user',)) -
Project migration to django data
Can i migraine my project from jam.py to Django? Without any change in the code or rewriting it to suit the framework? Or do you prefer to create my project on Django in the first place -
How can i stored verification code that send from register page to confirm page?
There is registration form that has mobile number and password for register,when person inter the info and submit,verification code sent for him,i want to access the verification code that sent in register page,that i can to compare with code that person inter in in input. how can i access into verification code in the confirm page -
django: nginx + gunicorn: request.build_absolute_uri() function not accounting for the port
I have the following code running in production The Nginx config is as follows: # first we declare our upstream server, which is our Gunicorn application upstream hello_server { # docker will automatically resolve this to the correct address # because we use the same name as the service: "djangoapp" server webapp:8888; } # now we declare our main server server { listen 8558; server_name localhost; location / { # everything is passed to Gunicorn proxy_pass http://hello_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Nginx server has port forwarding: 8555:8558 And the gunicorn command running is gunicorn --bind :8888 basic_django.wsgi:application Now in my browser i open this url: http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email Now my code in one of my views is prev_url = request.META['HTTP_REFERER'] # EG: prev_url = http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email # we want to get the url from namespace . We use reverse. But this give relative url not the full url with domain login_form_email_url_reverse = reverse("login_register_password_namespace:user_login_via_otp_form_email") # EG: login_form_email_url_reverse = "/login_register_password/user_login_via_otp_form_email" # to get the full url we have to use do the below login_form_email_url_reverse_full = request.build_absolute_uri(login_form_email_url_reverse) # EG: login_form_email_url_reverse_full = "http://127.0.0.1/login_register_password/user_login_via_otp_form_email" I am execpting prev_url and login_form_email_url_reverse_full to be same but it differs prev_url domain is http://127.0.0.1:8555 whereas login_form_email_url_reverse_full … -
changing navbar icons to active with django-Javascript
I have made a navbar with bootstrap4 and I want to toggle the icon of current page to active. Currently, I am using <li class="nav-item"><a href="/" id="A" {% if request.path == "/" %} class="nav-link active" {% else %} class="nav-link" {% endif %}>Home</a></li> <li class="nav-item"><a href="/blog" id="B" {% if request.path == "/blog/" %} class="nav-link active" {% else %} class="nav-link" {% endif %}>Blog</a></li> what I would like is a simpler way with use of url names that could activate a script like this: {% if request.path == '/' %} <script> document.getElementById("#A").classList.add('active'); if ( document.getElementById("#A").classList.contains('active') ) document.getElementById("#A").classList.toggle('active'); </script> {% elif request.path == '/blog/' %} <script> document.getElementById("#B").classList.add('active'); if ( document.getElementById("#B").classList.contains('active') ) document.getElementById("#B").classList.toggle('active'); </script> {% endif %} Could there be an easier way? Please suggest to highlight the active page icon on navbar to toggle styles. Thank you -
i want to move to my index page from anywhere in the app but got struck in the detailed generic view in Django
i am new to django and covered all the nooks and corners of it but i was struck at internal URL routing. i am completely succeeded in transforming my existing application into Django everything works fine but the issue is whenever i click on the logo i want to go back to my index page but that is not happening the path /index.html is adding in the last of my existing path what may be the reason. here is my URL.py file path('',views.home,name='home'), path('index.html',views.home,name='home'), path('easy.html',views.Easy.as_view(),name='title'), path('medium.html',views.Medium.as_view(),name='medium'), path('hard.html',views.Hard.as_view(),name='hard'), path('contribute.html',views.contribute,name='contribute'), path('contact.html',views.contact,name='contact'), path('about.html',views.about,name='about'), path('problems',views.problems,name='problems'), path('action',views.action,name='action'), path('detail.html',views.detail,name='detail'), path('detail.html/<slug:pk>/',views.DetailView.as_view(),name='detail') i can get back to any location in my when when i was on the navbar and normal application but the only problem arises when i entered into a detailed view which is a generic view. http://127.0.0.1:8000/detail.html/2/ this is how i entered a generic view which will display all the fields of record with PK=2. it's working fine. but now i want to get back index file by clicking on my logo then the link changes as follows. http://127.0.0.1:8000/detail.html/2/index.html i know my url.py file cannot identify this hence raising the 404 error. how to get rid of this? please help. by the way ,the below code … -
Using subdomain to set variable and display localized version of Django apps/sites
I have installed Django-modeltranslation, which creates additional fields to translate into additional language from a base field. The default language shown is base on the LANGUAGE_CODE in settings.py For example: LANGUAGE_CODE = 'de' will show the German version of the site. I want to use subdomain to set the variable for LANGUAGE_CODE and display to users to the appropriate language version of the site. For example: de.site.com subdomain 'de' will set the LANGUAGE_CODE to 'de' and show the website in German. vs. www.site.com subdomain 'www' will set the LANGUAGE_CODE to 'en_us' and show the website in American English. How do you do this? Is there a better implementation to get to the same point? -
CSS button won't change color
I'm trying to edit a template I've downloaded on the internet, by changing some colors. However, when I change the color in the css file, it doesn't change it on the website: HTML: <div class="user-panel"> <a href="https://example.com" target="_blank">Link</a> </div> CSS: .user-panel { float: right; font-weight: 500; background: #ffb320; padding: 8px 28px; border-radius: 30px; } This is how I import the .css file: <link rel="stylesheet" href="{% static 'css/style.css' %}"/> So what I did was changing #ffb320 to #cc0000 to have red instead of yellow, saved the file, and reloaded the page, but the color didn't change. Same goes for font size, etc... The only thing that did work was using style='font-size:20px' for the font size. What am I doing wrong here? -
Best way to increase post view count
I need to implement a way to increase view count for my posts when the post is viewed on the client side. For now, I won't be handling removing duplicate views by refreshing. If PATCH or PUT is sent to the server with the viewcount + 1 on client side, viewcount will be overridden if multiple users use my service. Is creating a new endpoint only for increasing the view count the best practice? If so, what would be the correct URI staying RESTful? (POST /post/count ?) -
How do I solve the problem in I mean them
enter image description here CrispyError at /accounts/login/ |as_crispy_field got passed an invalid or inexistent field -
Authorize user by sessionid axios
I am creating my e-commerce app(django-oscar api) and I would like to pass sessionid in my requests to authorize user. Everytime when i refresh my page i get a new user with no products in basket instead of adding products to my actual basket. Even withCredentials dont help. const session = axios.create({ withCredentials: true }); useEffect(() => { const data = { url: "http://127.0.0.1:8000/api/products/2/", quantity: 1, } console.log(data) session.post('http://127.0.0.1:8000/api/basket/add-product/', data) .then(res=>{ console.log(res.data) }) .catch(err=>{ console.log(err) }) }, []); In Postman everything works fine and products are added to correct basket [ { "url": "http://127.0.0.1:8000/api/baskets/77/lines/26/", "product": "http://127.0.0.1:8000/api/products/2/", "quantity": 3, "attributes": [], "price_currency": "PLN", "price_excl_tax": "417.00", "price_incl_tax": "417.00", "price_incl_tax_excl_discounts": "417.00", "price_excl_tax_excl_discounts": "417.00", "is_tax_known": true, "warning": null, "basket": "http://127.0.0.1:8000/api/baskets/77/", "stockrecord": "http://127.0.0.1:8000/api/products/2/stockrecords/1/", "date_created": "2020-05-07T12:00:00.190733Z" } ] -
how to have database relationship with the active data. in django
i have some active and non active data's in EVENT models and active data has the VISITORS form to fill ..so far i have tried OnetoOne relationship but it didn't succeed ..i am getting both active and non active field in VISITORs model..thank you for your time. here is models.py class Event(models.Model): event_id = models.AutoField Event_Name = models.CharField(max_length=50) description = RichTextField() date_And_time = models.DateTimeField() location=models.CharField(max_length=50) slugs = models.SlugField(max_length= 200,default="") picture = models.ImageField(upload_to='wildlife/picture', default="") active = models.BooleanField(default=False) class Meta: ordering = ["date_And_time"] def __str__(self): return self.Event_Name class Eventvisitor(models.Model): event = models.OneToOneField(Event, on_delete=models.CASCADE, related_name="eventvistor",default="") name = models.CharField(max_length=50) email = models.CharField(max_length=70, default="") phone = models.CharField(max_length=20,default="") date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date'] def __str__(self): return self.email -
Django manager in lookup fields
I have a SoftDeletableModel named Offer: class Offer(SoftDeletableModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='offers') order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name='offers') price = models.PositiveIntegerField() I am using below query to get all Orders that current user has an offer in it. Order.objects.filter(offers__user=request.user) but it counts deleted offers in lookup query. for example, if a user delete his offer from an order, this query returns that order too. an other example is something like this: Order.objects.filter(offers=48). offer 48 is removed but i get result from this query too. does django use default manger for lookup fields? -
How to disable "HTML" tab in DRF Browsable API but keep "Raw" tab available
When using more complicated representation schemas (e.g. nested objects and lists), the "HTML" form part of the Browsable API in Django REST Framework becomes mostly unusable. How can I disable it while still keeping the rest of the Browsable API available, including the ability to POST/PUT/PATCH data using the other "Raw" tab? -
how to pass a QuerySet instance to serializer?
I'm using raw sql (using orm is working) for fetching products and i'm getting this error Got AttributeError when attempting to get a value for field `name` on serializer `ProductSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `tuple` instance. Original exception text was: 'tuple' object has no attribute 'name'. This is the get function: def get(self, request, store_id, format=None): with connection.cursor() as cursor: user = request.user check_auth = get_object_or_404( Store, id=store_id, owner_id=user.id) if check_auth != None: connection.cursor() cursor.execute('SELECT * FROM products') products = cursor.fetchall() serializer = ProductSerializer(products, many=True) return Response(serializer.data) raise Http404 and here's the serializer class: class ProductSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) category = CategorySerializer() class Meta: model = Product fields = ['id', 'store_id', 'name', 'summary', 'description', 'category', 'main_image', 'price', 'offer_price', 'cost', 'available_quantity'] -
Google Cloud PubSub - How to send multiple arguments to the Cloud Function
I have been using Google Cloud PubSub to trigger Google Cloud Functions. Until this point I have been using a single argument "uuid", now I need to send also development/production flag. Here below is the publisher in Google App Engine/Django: publisher = pubsub_v1.PublisherClient() topic_name = 'projects/project/topics/cloudfunction_topic' message_to_publish = video.uuid publisher.publish(topic_name, data=message_to_publish.encode('utf-8'), spam='') Here below is the subscriber section in GCF: if os.getenv('GCF', None): uuid = base64.b64decode(event['data']).decode('utf-8') How should I change this so there can be multiple arguments (video.uuid, production/development) in the message ? -
Django url pattern data
If inside of urls.py I had a url pattern that depended on input sent to it from a template, what data would be sent to the url, and what data to the view? For example, urls.py:path('post/<int:post_id>/<str:post_title>', views.view_post, name='view_post'), blogposts.html template: <a href="{% url 'blogs:view_post' post.id post.title%}">Read More</a> views.py: def view_post(request, post_id, post_title):. What if I wanted only the post id to be sent to the view, but for the url to look the same? -
I am creating a project in Pycharm, I am working on django, whenever I am installing OpenCv and trying to use it I am getting following error
Traceback (most recent call last): File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy__init__.py", line 142, in from . import core File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core__init__.py", line 24, in from . import multiarray File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core\multiarray.py", line 14, in from . import overrides File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core\overrides.py", line 16, in add_docstring( RuntimeError: implement_array_function method already has a docstring Traceback (most recent call last): File "C:/Users/Dell/Desktop/pp/test2/templates/ex.py", line 1, in import cv2 File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\cv2__init__.py", line 5, in from .cv2 import * ImportError: numpy.core.multiarray failed to import -
How to store multiple values on a django model field
I have a model where I store the recurring sessions on my gym. DAYS_OF_WEEK = ( (0, _("Monday")), (1, _("Tuesday")), (2, _("Wednesday")), (3, _("Thursday")), (4, _("Friday")), (5, _("Saturday")), (6, _("Sunday")), ) class RecurringSession(models.Model): session = models.ForeignKey(SessionType, db_index=True, on_delete=models.CASCADE) dayofweek = models.PositiveSmallIntegerField(choices=DAYS_OF_WEEK) time = models.TimeField() However some classes happen more than once a week. Whats the best way to store multiple values (between 1 to 7) on that modelfield? I'm using Django Mysql 8.0, and from what I understand it supports JSON field but from the django docs it seems that is only supported by Postgres so far. I was inclined to So I'm inclined to change the dayofweek model field to a JsonModel Is there a specific django way to do this? Maybe storing a charfield with comma-separated values? I wont need to search by that field. Using Django 3.0.6, Python 3.8.2, and MySQL 8.0.20. thanks -
How to make Django Admin TabularInline sortable by custom field?
In Django Admin, it's easy to create a custom field on the model list page, e.g.: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('id', 'field1', 'field2', 'custom_field3') def custom_field3(self, obj): return obj.get_custom_field3_display() custom_field3.short_description = 'Custom Field 3' custom_field3.admin_order_field = 'field3' # makes column header sortable MyModel.field3 will be used to sort the now clickable "Custom Field 3" column header on the model list page. How can I achieve the same on an inline model? I can easily define a custom field in the same way, but the admin_order_field line doesn't achieve the same result: class MyModelInline(admin.TabularInline): model = MyModel fields = ('id', 'field1', 'field2', 'custom_field3') def custom_field3(self, obj): return obj.get_custom_field3_display() custom_field3.short_description = 'Custom Field 3' custom_field3.admin_order_field = 'field3' # doesn't seem to have any effect