Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pdfkit image not embedded using Django
I'm converting a protected webpage into pdf using Django and this solution. The solution works great except the part that the webpage contains images which do not show up in the pdf and i get an error Warning: Failed to load file:///media/images/main/logo.jpg (ignore) I'm currently using from_string method as follows pdfkit.from_string(msg_html, 'testing123.pdf') #msg_html contains html string with images -
Django TestCase: GET request should return 404 but return 200 in my test...?
I have a pdf function that print a pdf resume for example, this function is called with url /randomization/pdf/?patient=CIV-TR-001&medicament=8&type=1 if GET parameters are missing or not valid, it return a 404 or 500 error and it is the correct behavior I want to make a test for that but even if I pass empty 'patient' in my test, it always return status_code=200 (/randomization/pdf/?patient=&medicament=8&type=1) wherease when I call this url in my app, I am correctly redirected to my 404 page... I don't understand why url.py app_name='randomization' urlpatterns = [ path('pdf/', views.pdf, name='pdf'), ] views.py @login_required def pdf(request): ... # Données du formulaire de confirmation de randomisation patient = get_object_or_404(Randomisation, ran_num = request.GET.get('patient')) ... if request.GET.get('medicament') == '': med = None else: med = request.GET.get('medicament') dru = get_object_or_404(Medicament, med_ide = med) ... return FileResponse(buffer, as_attachment=True, filename=form + ' ' + pat +'.pdf') test.py class IndexPageTestCase(TestCase): def setUp(self): self.client = Client(HTTP_ACCEPT_LANGUAGE='en') self.pays = Pays.objects.create(pay_ide = 1,pay_nom_eng = 'Ivory Coast',pay_nom_fra = 'Côte d Ivoire',pay_abr = 'CIV') self.region = Region.objects.create(reg_ide = 1,pay = self.pays,reg_nom = 'Region 1',reg_abr = 'RE1') self.site = Site.objects.create(sit_ide = 1,reg=self.region,sit_typ = 'National',sit_nom_eng = 'PACCI',sit_nom_fra = 'PACCI',sit_abr = 'PA') self.user = User.objects.create_user('Slater','slater@surfeur.com','mereva2019') self.profile = Profile.objects.create(user=self.user,site = self.site) self.patient = Randomisation.objects.create(ran_num='CIV-TR-001',ran_dat='2020-03-09',ran_inv='Fanning',ran_pro=1,ran_crf_inc=1,ran_tbc=3,ran_crf_eli=1,ran_cri=1,ran_sta=1,ran_vih=0,ran_bra=4,ran_med='AAA',ran_log_dat=timezone.now(),ran_log_sit='TR') self.medicament … -
How to Delete or Ignore serializer.data object in serializer.py?
I need to delete serializer.data object in serializer, because i'm having some record in my table. But the entire record details is present in other microservice, Once someone called my api i need to call that service to get the data. But if the record is empty, i need to ignore this object. I can do this view, but it's possible to do in Serializer.py. Check the reference code: class CourseSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() def get_user(self, obj): token = self.context['request'].META['HTTP_TOKEN'] username = get_user_details_from_id(str(obj['user']), token, name=1) if username: return username else: obj = {} class Meta: model = Course fields = ('user', 'total_score') I want to ignore the record in SerializerMethodfield if the username is empty -
Is it possible to have default values of TextFields refer to txt files?
I am building a basic system that allows users to send templated emails in Django. I have a field in my email model that provides the content for the email: class Email(models.Model): message = models.TextField(_("Message"), blank=True) I want to specify default content, however the message itself could be quite long. Is there any way to have the default value refer to a text file (or any file) rather than have this in the model itself? E.g. class Email(models.Model): message = models.TextField(_("Message"), blank=True, default='mytextfile.txt') Is much better than class Email(models.Model): message = models.TextField(_("Message"), blank=True, default='"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia ...') -
How to setup connection to MySql database with gitlab CI/CD
I'm trying to set up automatic testing of django project using CI/CD gitlab. The problem is, I can't connect to the Mysql database in any way. gitlab-ci.yml services: - mysql:5.7 variables: MYSQL_DATABASE: "db_name" MYSQL_ROOT_PASSWORD: "dbpass" MYSQL_USER: "username" MYSQL_PASSWORD: "dbpass" stages: - test test: stage: test before_script: - apt update -qy && apt-get install -qqy --no-install-recommends default-mysql-client - mysql --user=$MYSQL_USER --password=$MYSQL_PASSWORD --database=$MYSQL_DATABASE --host=$MYSQL_HOST --execute="SHOW DATABASES; ALTER USER '$MYSQL_USER'@'%' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASSWORD'" script: - apt update -qy - apt install python3 python3-pip virtualenvwrapper -qy - virtualenv --python=python3 venv/ - source venv/bin/activate - pwd - pip install -r requirement.txt - python manage.py test apps With this file configuration, I get error ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) What have I tried to do add to mysql script tcp connection unstead socket mysql --protocol=TCP --user=$MYSQL_USER --password=$MYSQL_PASSWORD --database=$MYSQL_DATABASE --host=$MYSQL_HOST --execute="SHOW DATABASES; ALTER USER '$MYSQL_USER'@'%' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASSWORD'" And in this case I got ERROR 2002 (HY000): Can't connect to MySQL server on 'localhost' (99) How do I set up properly? -
generate password when creating a user by HR and send email to the created user to log in ,in django
I am beginner for Django. How can i generate a password and send the generated password to the user with its first name and last name to its email, and make the password field doesn't appear when i create the user through the HR. I also searched on the internet i got some codes and ideas but i don't know when to put them in class based when i inherit the AbstractBase. The code is as follows . but where i am going to put it password = User.objects.make_random_password() user.set_password(password) -
needs to have a value for field "id" before this many-to-many relationship can be used
While using bulk_create for my slots. I am always getting the error : ValueError(u'"<Schedule: 10:00:00, 01:00:00>" needs to have a value for field "id" before this many-to-many relationship can be used.',) The Code I have written is as follows: clients = Client.objects.filter(id__in=client_ids) fromuidaylabels = Label.objects.filter(id__in=label_ids, uidaylabel__isnull=False, datelabelmap__isnull=True).annotate(dayval=F('uidaylabel__day')).values('dayval','client','id') fromdayvals = dict([(e['dayval'], e) for e in fromuidaylabels]) touidaylabels = Label.objects.filter(client__id__in=client_ids, uidaylabel__day__in=fromdayvals.keys()).annotate(dayval=F('uidaylabel__day')).annotate(maxid=Max('id')).values('dayval', 'maxid','client') todayclient = {} for e in touidaylabels: todayclient[e['client']] = todayclient.setdefault(e['client'], []) + [e['dayval']] todayclientstocreate = {} for client_id, dayvals in todayclient.items(): todayclientstocreate[client_id] = list(set(fromdayvals.keys()) - set(todayclient[client_id])) day_slots = Schedule.objects.filter(label__in=[e.get('id') for e in fromuidaylabels]) day_slot_mapping = {} for sc in day_slots: day_slot_mapping[fromuidaylabels.values_list("dayval", flat = True).get(id = sc.label_id)] = day_slot_mapping.setdefault(fromuidaylabels.values_list("dayval", flat = True).get(id = sc.label_id), []) + [sc] for sc in date_slots: date_slot_mapping[fromuidatelabels.values_list("dateval", flat = True).get(id = sc.label_id)] = date_slot_mapping.setdefault(fromuidatelabels.values_list("dateval", flat = True).get(id = sc.label_id), []) + [sc] sc_list = [] for day, slots in day_slot_mapping.items(): for label_details in touidaylabels: label = Label.objects.get(id = label_details['maxid']) client = Client.objects.get(id = label_details['client']) for slot in slots: slot.pk = None slot.client = client slot.label = label sc_list.append(slot) if sc_list: SlotPlAssociation.objects.bulk_create(sc_list) Here the last line 'SlotPlAssociation.objects.bulk_create(sc_list)' pops the error - AttributeError: 'Schedule' object has no attribute 'playlist_id'. I added the other values to the slots, but … -
Django nested objects, different serializers GET and POST
this is a follow-up to this question I had here. I can now POST a new AP object using user Primary Key and after commenting this line in the AP serializer user = UserIndexSerializer(): Postman request: { "user":1, "name":"Max AP 05" } However the problem that I now have is that the initial UserIdexSerializer is rendered useless. This serializer determines the fields to show in a GET request but in consequence imposes the fields required in a POST request. What I'm trying to do is: POST a new AP object only using the user ID Show the UserIndexSerializer fields during a GET request (first_name, last_name, but not the ID) How can I make this work? I have found and read this post. I tried using different views, one for listing my models and one for creating a new one: from rest_framework import serializers from ..models.model_art_piece import AP from .serializers_user import * class APIndexSerializer(serializers.ModelSerializer): user = UserIndexSerializer() class Meta: model = AP fields = [ 'id', 'user', 'name' ] class APCreateSerializer(serializers.ModelSerializer): user = UserIDSerializer() class Meta: model = AP fields = [ 'id', 'user', 'name' ] def create(self, validated_data): ap = AP.objects.create(**validated_data) return ap class APDetailsSerializer(serializers.ModelSerializer): class Meta: model = AP … -
Count List of Objects inside JSONField in Django
class TopCountries(models.Model): top_countries = JSONField(null=True) top_countries is JSONField 'top_countries': [ {'country_code': 'AX', 'country_name': 'Åland Islands'}, {'country_code': 'AL', 'country_name': 'Albania'}, {'country_code': 'DZ', 'country_name': 'Algeria'} ] I am new to advanced queries. I've tried the query below but it does not give me the desired output. Query: UserProfile.objects.aggregate(Count('top_countries')) Output: {'top_countries__count': 1} Desired Output: {'top_countries__count': 3} -
Wagtail large list within stream field block
We use wagtail for our blogs that are part of an eCommerce site. When we want to add a product to the blog as it stands we have to put the exact product name in which then matches on save. As names can change this then breaks that blog which isnt ideal. What we would like to do is add a field to our streamfield block that lets you pick from our list of products, however as we have 200k+ products and there might be up to 20 products on each blog loading the list into a dropdown is no good. What we need is to replicate what we do in Django admin using django-autocomplete-light where you start typing and get results based on that rather than loading the list into the HTML. What we cant work out is how to do that within a streamfield block, I have seen libraries like "Wagtail Autocomplete" however it seems you can only use that as a panel rather than within a block. As far as we can see you can only use sub-classes of wagtail.core.blocks or they dont show up in the interface. Any ideas? Thanks in advance! -
Overriding Django RelatedManager and Queryset to filter on a field in the Through Model
I have two models that are linked via Many-To-Many field via third Through Model. The Through Model has some extra fields in it. I want to override the RelatedManager to produce some custom QuerySets that use the extra fields in the Through Model. The caveat is that my Through Model is created using a subclass/mixin that defines the extra fields. What I want to be able to do is get all the Gene objects related to the SampleBatch that have an active status of 1 in the SampleBatchGene instances linking the Many-to-Many fields: In [1]: SampleBatch.objects.get(sample__lab_number="18_11998").genes.active() Out[1]: <QuerySet [<Gene: BAP1>]> This is what I have so far: class SampleBatch(models.Model): sample = models.ForeignKey(Sample, on_delete=models.CASCADE) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) genes = models.ManyToManyField( "Gene", through='SampleBatchGene', related_name='samplebatches', blank=True, through_fields=('samplebatch', 'gene') ) class Meta: managed = True db_table = 'sample_batch' unique_together = (('sample', 'batch'),) verbose_name_plural = "Sample batches" def __str__(self): return '{}-{}'.format(self.sample, self.batch) class Gene(models.Model): gene_id = models.BigAutoField(primary_key=True) gene_name = models.CharField(unique=True, max_length=255, db_index=True) hgnc_number = models.IntegerField(unique=True, db_index=True) class Meta: managed = True db_table = 'gene' def __str__(self): return self.gene_name class ActiveQuerySet(models.QuerySet): def active(self): return self.filter(active=1) def inactive(self): return self.filter(active=0) class LinkMixin(models.Model): ACTIVE_CHOICES = ( (0, 'Inactive'), (1, 'Active') ) activated = models.DateTimeField(default=timezone.now) active = models.IntegerField( … -
django unable to show search result
I'm trying to do a search function on my home page. What it should does is that when the user clicked the on the Search button, the url should change from http://127.0.0.1:8000/ to http://127.0.0.1:8000/search.html and return the search result. Currently after pressing the search button it still stays at the home page and does not show the search result. I dont know what went wrong. views.py class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def SearchFilter(request, Item): items = Item.objects.all() myFilter = ItemFilter(request.GET, queryset=items) items = myFilter.qs context = { 'Item': items, 'myfilter': myFilter } return render(request, "search.html", context) filters.py import django_filters from .models import * class ItemFilter(django_filters.FilterSet): class Meta: model = Item fields = { 'title': ['icontains'], 'price': ['exact', 'contains'], 'discount_price': ['exact', 'contains'], 'category': ['exact', 'contains'], } home.html <form class="form-inline" method="get"> <div class="md-form my-0"> {{myFilter.form}} <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search"> <button class="btn btn-primary" type="submit">Search</button> </div> </form> -
Python Sending email
I have this code for sending emails. An email is supposed to be sent to an Admin when a staff applies for leave and another one back to the staff as soon as the leave application is processed. I have the first part working ok. An admin user is indeed receiving the leave application email but once they processes it, the staff isnt receiving the feedback email. I suspect am getting it wrong how am grabbing the user email from the leave_obj but can figure out any other way. To the best of my knowledge user.email should work since there's a foreign key relationship between the leave, employee and user models. What am I missing? Below is all my relevant code. send_email function: def send_email( name: str, email: str, subject: str, message: str, obj: object = None, cc_list: list = None, template: str = "generic", template_path: str = "C:/Projects/hr_app/humanresource/src/templates/email", ): context = { "name": name, "subject": subject, "message": message, "object": obj, "SITE": Site.objects.get_current(), } email_subject = render_to_string( f"{template_path}/{template}_email_subject.txt", context ).replace("\n", "") email_txt_body = render_to_string( f"{template_path}/{template}_email_body.txt", context ) email_html_body = render_to_string( f"{template_path}/{template}_email_body.html", context ).replace("\n", "") subject = email_subject from_email = settings.DEFAULT_FROM_EMAIL to_email = f"{name} <{email}>" text_content = email_txt_body html_content = email_html_body … -
Django flatpages The empty path didn't match any of these
On the administration page, I set the URL for the Django flat pages to "/", which is expected to be displayed as the home page at http://127.0.0.1:8000/. Doing so I encountered an error: Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in core.urls, Django tried these URL patterns, in this order: admin/ <path:url> The empty path didn't match any of these. But if I go to http://127.0.0.1:8000// with double slash then the home page is displayed correctly. My only urls.py file looks like this: from django.contrib import admin from django.urls import include, path from django.contrib.flatpages import views urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += [ path('<path:url>', views.flatpage), ] And I took all the code completely from the official guide. How to display the django flatpage homepage at http://127.0.0.1:8000/? -
Celery/Kombu SimpleQueue.get() never returns even when message appears in queue. Why?
This has taken some time to nail this far and gets more mysterious with every step. I'm using a Kombu SimpleQueue quite effectively to send messages to a Celery task. I though all my problems solved to be honest as that's what I need and SimpleQueue delivers it elegantly. Until ... To put it into context, I have a Django site, and a Celery task all working beautifully together. I can put a message on the queue and read it as follows: from time import sleep from celery import current_app from celery.utils.log import get_logger from kombu.simple import SimpleQueue logger = get_logger(__name__) def q_name(task_id): return f'MySimpleQueueFor_{task_id}' def send_to_task(task_id, message): with Connection(current_app.conf.broker_write_url) as conn: q = conn.SimpleQueue(q_name(task_id)) q.put(message) print(f'Sent: {message} to {q_name(task_id)}') q.close() def check_for_message(q, task_id): try: message = q.get_nowait() # Raises an Empty exception if the Queue is empty payload = message.payload message.ack() # remove message from queue q.close() return payload except q.Empty: return None @app.task(bind=True) def my_task(self, *args, **kwargs): with Connection(current_app.conf.broker_read_url) as conn: task_id = self.request.id q = conn.SimpleQueue(q_name(task_id)) while True: message = check_for_message(q, task_id) logger.info(f'Received: {message} from {q.name}') sleep(0.1) With a task_id in hand I can send any message to the task I and I can see the messages … -
A Different Way to Write =>
I don't understand how this function works. And would like the "novice," more detailed approach to specifically replace "=>" in the code. Thanks for helping a newbie! def __str__(self): return f"User: {self.observer.pk} => Habit: {self.habit.pk}" -
'AnonymousUser' object has no attribute '_meta' error in Django login function
I'm having problem in the built-in login function in Django. Here is the views.py code: def login_page(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid: user = form.get_user() login(request, user) return redirect('index') else: form = AuthenticationForm() return render(request, 'login.html', {'form':form}) And below is my html code. <form action="{% url 'login' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Log in"> </form> As soon as I click the 'Log in' button, it gives an error that says: 'AnonymousUser' object has no attribute '_meta' I don't see which part is wrong. I very much appreciate your help. :) -
{**Defaults, **url_pattern.default_kwargs}, TypeError: 'function' object is not a mapping
urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('CORE_INDEX.core_index_urls')), path('about/', include('CORE_INDEX.core_index_urls')), path('privacy/', include('CORE_INDEX.core_index_urls')), path('player/', include('PLAYER.player_urls')), path('member/', include('MEMBER.member_urls')), ] Error: {**defaults, **url_pattern.default_kwargs}, TypeError: 'function' object is not a mapping [09/Mar/2020 10:41:16] "GET /admin/ HTTP/1.1" 500 121679 -
Not able to display images from static folder using Django
This is my home.html I'm not able to display the images in static/images/ folder. Although *[09/Mar/2020 15:52:09] "GET /static/images/mona.jpg HTTP/1.1" 404 1669 * is displayed in terminal. <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% block content %} {% load static %} <title>Home</title> <link rel="stylesheet" href={% static '/css/style.css' %} /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </head> <body> {% include "includes/header.html" %} <div class="pt-5"> <div class="card d-inline-block"> <img src={% static 'images/mona.jpeg' %} alt="Avatar" style="width:100%;"> <div class="container"> <h4><b>Mona Lisa</b></h4> <p><a href="#">Architect & Engineer</a></p> </div> </div> <div class="card d-inline-block"> <img src={% static "images/mona.jpg" %} alt="Avatar" style="width:100%"> <div class="container"> <h4><b>The Scream</b></h4> <p><a href="#">Architect & Engineer</a></p> </div> </div> </div> {% include "includes/footer.html" %} {% endblock content %} </body> -
Django how to show modal after the user's updating their data
I hope my title is enough to understand what my problem is, i have this code in my html <form method="post" action="/reactivate/" onsubmit="openModal()" id="myForm" enctype="multipart/form-data" autocomplete="on">{% csrf_token %} {% for me in ako %} Date: <input type="hidden" value="{{me.enddate}}" name="date" id="start_date">{{me.enddate}} <input type="hidden" value="{{me.id}}" name="id" hidden><p>{{me.Email}}</p> {% endfor %} <select id="days"> {% for perfume in s %} <option value="{{perfume.adddate}}" data-days="{{perfume.adddate}}" id="days">{{perfume.product}} - {{perfume.adddate}} Days</option> {% endfor %} </select> <br><br><br> <label>Deadline:</label><br> <input type="date" name="endate" id="end_date" readonly/> <input type="submit" value="Sign up"/> </form> this is my modal code in html <div class="modal fade" tabindex="-1" role="dialog" id="myModal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> <p>One fine body&hellip;</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> I want to show this modal when after the user update the date and this is my views.py def reactivate(request): id = request.POST.get('id') date = request.POST.get('endate') update = User.objects.get(id=id) update.enddate = date update.save() the error says this is my script <script> $('#myForm').on('submit', function(e){ $('#myModal').modal('show'); e.preventDefault(); }); </script> -
DateTimeField widget in django isn't saving the data. It keeps on saying enter valid date and time
I am following this tutorial : Simple is better than complex to add a datetimepicker widget to a django crispy form. The icon appears in the form and the date and time gets filled in the field as shown in the picture below : But it keeps on asking me to enter a valid date and time when I try to submit the form as shown below: My model looks as follows models.py class Ads(models.Model): company_name = models.CharField(max_length=50) # Company Name image = models.ImageField( upload_to='ad_images/',blank = True, null= True) # Adding multiple image according to device?? # Header, Content, Sidebar AD_CHOICES = ( ('H','header'), ('C','content'), ('S','sidebar'), ) ad_position = models.CharField(max_length=2, choices= AD_CHOICES, default='H') # profile_pic_status = models.BooleanField(default=True) # use duration field to decide which ad gets placed duration_start = models.DateTimeField(default=timezone.now) duration_end = models.DateTimeField(default=timezone.now) clicks = models.IntegerField(default = 0) url = models.CharField(max_length=50) # Add display status boolean data type to represent whether that image is the profile pic def __str__(self): return self.company_name My form looks like this: forms.my from django import forms from .models import Ads from .widgets import BootstrapDateTimePickerInput class PostForm(forms.ModelForm): duration_start = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput()) duration_end = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput()) class Meta: model = Ads fields = ['company_name', 'image', … -
How to fix DateRangeFilter in order the date widjet to appear properly
Using adminactions to my project I came up with the problem that my date widjet(the calendar) is not appearing to my form at all. I successfully install the django-admin-rangefilter and import it as well. my model class Order(models.Model): stem_date = models.DateField("STEM") delivery_date = models.DateField("Delivery Date") my admin.py from rangefilter.filter import DateRangeFilter, DateTimeRangeFilter list_filter = [('stem_date', DateRangeFilter), ('delivery_date', DateRangeFilter), ('cost_center')] I am using django version = 2.2.6 and python version 3.5.2 Have anyone any idea why my widjet is not loaded at all? -
static files problem, everything is loaded except some files style.css and js
my template didn't work and can't get static files but I did everything. I just can't get style.css but other files are loaded. only style and some js files isn't loaded but the path is not wrong . please help me this is an image of my folder and project tree Settings for Static and media. STATIC_URL = '/temfiles/' MEDIA_URL = '/mediafiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads/') X_FRAME_OPTIONS = 'SAMEORIGIN' my project URL file urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('froala_editor/', include('froala_editor.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my app URL file urlpatterns = [ path('', views.index, name = 'index'), path('<slug:slug>/', views.post_detail, name='Post Detail') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my Views File def index(request): Post_list = BlogPost.objects.all() template_name = 'front/index.html' return render(request, template_name,{"Post_list":Post_list}) def post_detail(request): return render(request, 'front/post_detail.html') my base template CSS example {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'front/css/style.css' %}"> Static Directory Tree image static directory tree with open folders browser inspect terminal picture style CSS URL in browser MY urls.py for static and media root -
Django got an unexpected keyword argument after solving 'collections.OrderedDict' object has no attribute
I am trying to solve the error: AttributeError: 'collections.OrderedDict' object has no attribute 'group_pk' when trying to add an url field to a serializer class in django. I read that I need to save my serializer data so I added serializer.save() before return serializer.data When I do that I get the error: Django got an unexpected keyword argument "linked_sites" I'm now facing this problem for 2 days, seems like its returning with more people. Here is my code: part of test-class: # New group name new_name = "New group name" sites = [self.test_site_3.pk] # Execute the patch operation response = self.client.patch( url, data={"name": new_name, "linked_sites": sites} ) # Test if there was no error self.assertEqual(response.status_code, status.HTTP_200_OK) serializer: class GroupPatchSerializer(serializers.ModelSerializer): linked_sites = serializers.ListField() name = serializers.CharField(required=False) url = serializers.HyperlinkedIdentityField( view_name="group-detail", lookup_field="group_pk", read_only=True ) class Meta: model = Group fields = ("id", "url", "name", "linked_sites") def validate_linked_sites(self, sites): def validate_name(self, name): view: def patch(self, request, group_pk): """ Add site to group, change an existing group's name. -id: The group's id """ user = request.user group_id = int(group_pk) group = Group.objects.filter(pk=group_id).first() # Check if the user has permission to edit the group details if not UserSiteGroup.objects.filter( usersite__user=user.id, group=group_pk ).exists(): raise PermissionDenied( "The user … -
Django how to set url based on model item.title?
I'm trying to create a very basic search like feature but I had no clue on how to do it. Appreciate if anyone could provide any source of help or information. I tried to use something like "{% url 'product' item.title %}" but it return an error Reverse for 'product' not found. 'product' is not a valid view function or pattern name. The end result is when the user click on the shirts tag, the home page should only show results related to shirts home.html <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">All <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Shirts</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Sport wears</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Outwears</a> </li> </ul> urls.py urlpatterns = [ path('', HomeView.as_view(), name='home'), path('product/<slug>/', ItemDetailView.as_view(), name='product') ] models.py class Item(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title[enter image description here][1]