Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you have button inside a tag
So my problem is that I have those 2 buttons inside this card and when i click them it redirects to a link which the card itself is redirecting, so can i make this work? <a class="panel-product-div-a" href="{{ item.get_absolute_url }}"> <div style="color: {{ item.checks_color }}" class="p-checks"> <p>{{ item.checks|safe|linebreaks }}</p> </div> <span> <img {% if item.image %} src="{{ item.image.url }}" {% else %} nop {% endif %} alt="ehm.."> </span> <h1 class="mdh2">{{ item.title }}</h1> <div class="panel-button-div"> <button onclick="window.location.href='{{ item.get_add_to_cart_url }}'" class="btn btn-lg btn-primary panel-btn">To cart</button> <button onclick="window.location.href='{{ item.get_absolute_url }}'" class="btn btn-lg btn-light panel-btn">More info</button> </div> <div class="con-div"> {% if item.discount_price %} <h1 class="mdh1-discount"> {{ item.price }}€ </h1> <h1 class="mdh1"> {{ item.discount_price }}€ </h1> {% else %} <h1 class="mdh1"> {{ item.price }}€ </h1> {% endif %} </div> </a> -
Redis installation Windows 10
I am having an issue where I need a feature from a later redis version than the latest one for windows, is there a way I can install a newer version in windows without a vm? -
Django cached sessions: Is using Redis ok?
Django documentation on configuring cached sessions says this: You should only use cache-based sessions if you’re using the Memcached cache backend. The local-memory cache backend doesn’t retain data long enough to be a good choice, and it’ll be faster to use file or database sessions directly instead of sending everything through the file or database cache backends. Additionally, the local-memory cache backend is NOT multi-process safe, therefore probably not a good choice for production environments. It specifically, only mentions Memcached. Does this mean Redis is not a good choice? -
Why using filter() giveswhat I want, by get() raises an error
I created cusom QuerySet and Manager to serialize my data. class UpdateQuerySet(models.QuerySet): def serialize(self): return serialize("json", self) class UpdateManager(models.Manager): def get_queryset(self): return UpdateQuerySet(self.model, using=self._db) class Update(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) objects = UpdateManager() Then, when I'am trying to get this data, it worked with this: json_data = Update.objects.filter(id=1).serialize() but raises AttributeError ('Update' object has no attribute 'serialize') with this: json_data = Update.objects.get(id=1).serialize() -
How to select students for teachers automatically in Django
This is my students class class Students(AbstractUser): mobile_number = models.TextField() My Teacher Class class Teacher(models.Model): students = models.TextField() How can associate 6 students to one teacher automatically in Django -
problem with django :__call__() missing 1 required keyword-only argument: 'manager'
so basically i am completing the project 2 of cs50 harvard course called commerce. i have a class named auction inside a model which has some fields and a user as mentioned in this picture.auction model i use django- admin interface to input the data. so when i try to add everything i get the error each time :"call() missing 1 required keyword-only argument: 'manager'" i need to solve this problem asap. -
What is the URL when I DELETE an object
I'm running a local server playing around with an API using Django. I have a model called 'Users' populated with a few objects, and am using DefaultRouter. I want to know what the URL would be if I were to DELETE a specific object from this model. For example, if I wanted to GET all of the users in this model, the URL would be: "localhost:8000/Users/". I found an explanation of this on the REST API website (below), however, I don't understand what any of the syntaxes means. What is {prefix}, {url_path}, {lookup} and [.format]? If anyone could provide an example of what this might be using a localhost that would be really helpful. Thanks -
Django Modal Close after submit
i have developed a simple form loading into bootstrap modal, the form gets rendered and everything is ok. however when i submit the form the modal does not submit and close as i get the Error of redirect is incorrect. i am using Bootstrap Modal without Jquery for ease of implementation, the form is loaded through the Detail View function and the submit is through another View function 'test1'. i get the following Error: NoReverseMatch at /split/3 Reverse for 'applicationdetail' with no arguments not found. 1 pattern(s) tried: ['applicationdetail/(?P[0-9]+)$'] below is my concept code : models.py: class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( max_length = 32 , null = False , blank = False ) class Score_Appeal(models.Model): appeal_score = models.ForeignKey(Startup, on_delete = models.CASCADE) appeal_evaluator = models.ForeignKey(User, on_delete = models.CASCADE) appeal = models.CharField ('Appeal', max_length = 100 , null = False , blank = False , choices = Choice.EVALUATION , default = '' ) appeal_comment = models.TextField(max_length = 100, blank = True) views.py: @login_required @inv_required def global_list(request): startup = Startup.objects.all() return render(request, 'inv_template/global_list.html', {'startup': startup}) @login_required @inv_required def applicationdetail(request, pk): obj = Startup.objects.filter(pk = pk) form = SplitForm1 … -
how to fix InternalError at /search when i search in Arabic for example using Django
Server error (500) when I try to search in any language other than English , I Make DEBUG = True and it show this error for me (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'") Exception Location: /home/example/virtualenv/django/3.7/lib/python3.7/site-packages/pymysql/err.py in raise_mysql_exception, line 109 and the problem i was search in Arabic word بحث in search box and when i do the search the URL show like this Request URL: https://example.com/search?q=%D8%B3%D8%B4%D9%8A%D8%B3%D9%8A&submit=Search Do not recognize Arabic letters or any language other than English -
Django group by one field and get max by other
I have this model: class Order(models.Model): symbol = models.CharField(max_length=30, default='') b_id = models.IntegerField(null = True, blank = True, unique=True) I use this for storing trade orders from exchange that I get from api the usual orders I get looks like this: #order1 (symbol='btc/usdt', b_id =1) #order2 (symbol ='btc/usdt, b_id=2) #order3 (symbol = 'eth/usdt', b_id=8) #order4 (symbol = 'eth/usdt', b_id=9) #b_id is unique id I get from exchange To get correct history of orders I need to get order with biggest b_id grouped by symbol so I need function that will return object something like: result = {'btc/usdt': 2, 'eth/usdt': 9} Right now I just use simple cycle: symbols=['btc/usdt', 'eth/usdt','link/usdt'] for symbol in symbols: last_order = Order.objects.filter(symbol=symbol).latest('b_id') since = last_order.b_id sinces[symbol]=since But it queries database to often. Any ideas how to reduce database calls? -
JSONDecodeError Expecting value: line 1 column 1 (char 0). (New to Django)
I am new to Django and currently, I am developing an eCommerce site. Facing this error -- JSONDecodeError Expecting value: line 1 column 1 (char 0). Can someone please help me out. Request Method: GET Request URL: http://127.0.0.1:8000/process_order/ Django Version: 2.2.8 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py in raw_decode, line 355 Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.2 Python Path: ['D:\pythonprac\ecommerce\Website', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py" in raw_decode 353. obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\pythonprac\ecommerce\Website\store\views.py" in processOrder 88. data = json.loads(request.body) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json_init_.py" in loads 348. return _default_decoder.decode(s) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py" in decode 337. obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py" in raw_decode 355. raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /process_order/ Exception Value: Expecting value: line 1 column 1 (char 0) -
How to solve KeyError in Django?
I have multiple Apps in my Django website, And i want to get the data from all Apps, I definds all the apps in settings.py file, and i created a function in admin.py file for display the data. But i am getting Keyerror, please check my code and let me know where i am Mistaking here is my settings.py file code.. ADMIN_ORDERING = [ ('manager', [ 'Products', 'ProductTemplates', ]), ] here is my admin.py file which is displaying the data in views.. def get_app_list(self, request): app_dict = self._build_app_dict(request) for app_name, object_list in settings.ADMIN_ORDERING: app=app_dict[app_name] app['models'].sort(key=lambda x: object_list.index(x['object_name'])) yield app i am getting error in this line app=app_dict[app_name] it's displaying KeyError at/ manager, and manager is my django project app name -
Duplicate results when querying using SearchVector
I have an abstract model class called PostType with a few submodels derived from it. The model looks like this: class PostType(models.Model): title = models.CharField( max_length=255, unique=True, verbose_name='Title' ) description = models.CharField( max_length=255, default='', verbose_name='Description' ) tags = models.ManyToManyField( to=Tag, blank=True, verbose_name='Tags' ) content = RichTextUploadingField( default='', verbose_name='Post Content' ) class Meta: abstract = True It has a related Tag model that looks like this: class Tag(models.Model): name = models.CharField( max_length=255, verbose_name='Name', unique=True ) description = models.TextField( verbose_name='Description', default='' ) In one of my views I am trying to query all of the subclasses, using a SearchVector and searching multiple fields: query = request.GET.get('s') from django.contrib.postgres.search import SearchVector get_qs_list = [model.objects.annotate( search=SearchVector('title', 'description', 'content', 'tags__name') ).filter(search=query) for model in models.PostType.__subclasses__()] Now, the search is returning all of the results that it should. However, for some reason it's returning duplicate results for some items. Sometimes I get two copies of the same item, sometimes three or four. The problem seems to go away if I remove 'tags__name' from the SearchVector, but I don't understand why. What am I doing wrong, and why does it work if I don't search the related field? -
Django | Render Plotly graph
I'm trying to pull a Plotly graph into a Django view. If I use the code of the Plotly graph inside views.py I have no problem on seeing the line chart, however, I'd like to move this code to a plots.py file and then import it into views.py so there's a better project structure. Current views.py from plotly.offline import plot import plotly.graph_objects as go def plotlyTest(request): x_data = [1,2,3] y_data = [4,3,6] stuff = go.Scatter( x=x_data, y=y_data, mode='lines', name='Stuff', opacity=0.8, marker_color='blue' ) data = [stuff] # Create figure fig = go.Figure(data=data) plot_div = plot(fig, output_type='div', include_plotlyjs=False, show_link=False, link_text="") context = { 'plot_div':plot_div, } return render(request, 'custom_app/plotly_test.html', context) Desired views.py (pseudo code) from apps.another_app import plots def plotlyTest(request): plot_div = testPlot context = { 'plot_div':plot_div, } return render(request, 'admin/plotly_test.html', context) plots.py from plotly.offline import plot import plotly.graph_objects as go def testPlot(request): x_data = [1,2,3] y_data = [4,3,6] stuff = go.Scatter( x=x_data, y=y_data, mode='lines', name='Stuff', opacity=0.8, marker_color='blue' ) data = [stuff] # Create figure fig = go.Figure(data=data) plot_div = plot(fig, output_type='div', include_plotlyjs=False, show_link=False, link_text="") return plot_div This seems to be more a Python logic than a Django logic. Maybe creating a class based view and use template tags should work? -
Django unable to load static files: Attribute error at /admin you need a private key to sign credentials
I have a docker image, which I deploy using Google Cloud Run. For static and media files I'm using Google Cloud Storage. Here is the relevant part of settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.environ.get('STORAGE_URL', default=BASE_DIR), "media") STATIC_ROOT = os.path.join(os.environ.get('STORAGE_URL', default=BASE_DIR), "static") DEFAULT_FILE_STORAGE = os.environ.get('STORAGE_BACKEND', default='django.core.files.storage.FileSystemStorage') STATICFILES_STORAGE = os.environ.get('STORAGE_BACKEND', default='django.core.files.storage.FileSystemStorage') GS_BUCKET_NAME = os.environ.get('GS_BUCKET_NAME') The environment values are: STORAGE_URL= https://storage.googleapis.com/<my-bucket-name>/ STORAGE_BACKEND=storages.backends.gcloud.GoogleCloudStorage GS_BUCKET_NAME=my-bucket-name After deployment, when I visit my google cloud run app url. I am not able to go to admin page. it gives the following error: AttributeError at /admin you need a private key to sign credentials.the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token. see https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-account for more details. Interestingly, the collectstatic command works flawlessly... When I deploy my image it copies static files to my storage bucket. But when accessing it through the url, it gives me this error. -
Django query objects by subset of possible foreign keys
I have a query: topics, that looks like topics = Topic.objects.filter(top_is_published=True, top_last_used_date__range=(issue.wir_issue_date - timedelta(days=7), issue.wir_issue_date)) And I want all the articles which have one of the objects in 'topics' as their foreign key. When I try to use a lookup like: articles = News.objects.filter(top_name=topics) or something similar, I get the error "ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing." I've searched for an example, but I can't find one. Thanks for any help. -
Scheduling Tasks in Django
I am new to Django. I built a program that lets teachers assign homework to students. The homework has a due date that is different for each student. I want to make it so that 1 hour before the homework is due for that particular student, they get sent an email. So, for example: Student 1 with HW due at 3 pm would get an email at 2 pm Student 2 with HW due at 1 am would get an email at 12 am How can I achieve this? Thanks!!! -
How to get request values from Django decorator
In my decorator: def check_user_identity(function): def wrap(request, *args, **kwargs): response_check_user = mock_response.check_user_identity(requested_data=request.data['msisdn']) if response_check_user['status'] == SUCCESS_CODE: return function(request, *args, **kwargs) return Response(data=INVALID_USER, status=status.HTTP_400_BAD_REQUEST) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap In my views: Here the request parameter has my values which i have requested to proceed. First of all decorator is called. I want to access my request data from the decorator. class VerifyWallet(APIView): @check_user_identity def post(self, request): logger.debug(msg=request.data) serializer = VerifyWalletSerializer(data=request.data) if not serializer.is_valid(): logger.error(msg=serializer.errors) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(data='success', status=status.HTTP_200_OK) -
Django forms: Accessing cleaned_data in clean() - not working?
Ok so I'm trying to write the clean() in a forms class. Issue: when accessing the values: name, age, height from the clean_data dict it is not returning the field values. Am I accessing the dictionary correctly? because the if condition isn't working correctly class PersonForms(forms.ModelForm): name = forms.CharField(max_length=20, help_text="Your Name") height = forms.DecimalField(help_text="height..") age = forms.IntegerField(help_text="age:") class Meta: model = Person fields = ('name', 'height') # Fields are validated in their own field_clean() method.clean() method is to validate any combination or # multiple fields with values relating to one another. def clean(self): print("clean...$$") # run the standard clean method first - this ensures # The ModelForm.clean() method sets a flag that makes the model validation step validate the uniqueness of # model fields that are marked as unique, unique_together or unique_for_date | month | year. cleaned_data = super(PersonForms, self).clean() # once the parent's clean function valids data - access fields via cleaned_data dictionary name = cleaned_data.get("name") age = cleaned_data.get("age") height = cleaned_data.get("height") if "max" not in name or age > 13: print("*************** name", name) raise ValidationError(_("Err, type %(value) as name or age %(age) invalid"), params={'value': name, 'age': age}, code='invalid1') -
Django: How to add Image of User in UserPostList View
I am trying to add the profile image of each user(designer) in the below list view For each designer, there is a profile image that has already been uploaded before I am just trying to get it and show it in the UserPost List View. Currently, with the below code, the designer image is not showing. Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted') def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) has_items = Item.objects.filter(designer__username=self.kwargs['username']).exists() context['has_items'] = has_items return context Here is the template {% if has_items %} <h1> Hello, this is {{ view.kwargs.username }} </h1> -------------------------------------- <img class="profile_image" src={{ designer.profile.image.url }}> <----------- I want it to appear {% else %} <h1>Hello, this is {{ view.kwargs.username }} </h1> -------------------------------------- <img class="profile_image" src={{ designer.profile.image.url }}> <----------- I want it to appear {% endif %} -
Migrate UUID PK to Django's Default PK
I made a mistake and made the PK of my model a UUID: id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) I want to revert it to Django's default, where every instance automatically has a PK, without having an ID model field. How can I do this? Thanks! -
Django Server Unable to Open Admin Page
I am following an online course on Django, and my browser fails to load the admin page. I created a job, added it to INSTALLED_APPS in settings.py, and added it in admin.py as follows: from .models import Job Register your models here. admin.site.register(Job) In urls.py I believe I have the standard admin url urlpatterns = [ path('admin/', admin.site.urls), path('home/', jobs.views.home, name='home'), ] I'm not sure if any other any information is needed but please ask if there is anything else. I start the server using python manage.py runserver and it can access /home okay, but if I change the url to admin or admin/ it says 'Firefox can’t establish a connection to the server at 127.0.0.1:8000.'.I've tried it on different browsers and the same outcome is reached. My question is similar to the one here: Django error browser is unable to connect at 127.0.0.1:8000/products/ and I tried all of the solutions there but none worked. I followed the tutorial very specifically, so I have no idea what is causing this. I am using Atom on a Windows 10 machine, the project is connected to a postgresql database. -
Django Polling App TypeError between Nonetype and datetime.datetime
I am practicing Django Polling App and get the following error when I try my admin site to open questions TypeError: '>=' not supported between instances of 'NoneType' and 'datetime.datetime' My models.py import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): # now = timezone.now() return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text It seems to work if I replace DateTimeField by DateField and use timezone.now().date() but the tutorial does not mention it. Am I doing something wrong ? -
NameError: name 'admin' is not defined (Django/GeoDjango)
I am in the process of building a web app using Django and GeoDjango (I am also following this tutorial) I am trying to register a new model in admin.py but after I do so I get the following error: NameError: name 'admin' is not defined I have checked my code carefully, and also tried adding django.contrib.gis.admin to installed apps for Django but this just returned an error because I already have 'django.contrib.gis listed. Here is my code, any help greatly appreciated: from django.contrib.gis.admin import OSMGeoAdmin from .models import Cafe # Register your models here. @admin.register(Cafe) class CafeAdmin(OSMGeoAdmin): list_display = ('name', 'location') And here is the model from django.contrib.gis.db import models # Create your models here. class Cafe(models.Model): name = models.CharField(max_length=100) location = models.PointField() address = models.CharField(max_length=100) -
djfractions in Django model - error "'DecimalFractionField' object has no attribute 'context'"
I'm looking to have a fraction field in a Django model. I've been trying using djfractions and it seems to be working and successfully adding a fraction value as a decimal to my (sqlite3) database, but when I try to review my database from the (local) server, I get the error "'DecimalFractionField' object has no attribute 'context'". Below is the attribute in my model that I'm using the fraction in, and the value I added to my database is 1/2, which gets translated to 0.5. ''' ingredient1_amount_fraction = djfractions.models.DecimalFractionField(verbose_name=None, name=None, max_digits=10, decimal_places=5, limit_denominator=None, coerce_thirds=True, null = True) '''