Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Not Displaying ID properly in admin page
I have a model that's a profile in a 1-1 relationship with the User model. class MyAppProfile(UUIDModel): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="myapp_profile") # Other fields for this app's profile go here used = models.BooleanField(default=False) def __str__(self): return f'{self.id} {self.pk}: MyApp Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) def create_user_profile(sender, instance, created, **kwargs): if created: MyAppProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=AUTH_USER_MODEL) When I view this in the admin page, it shows the ID for the user.id field instead of the id of the MyAppProfile. For example, for the one I manually created, it has user.id value of 4TeBms2K; and an ID of 4SrBSXw1. Yet when I view it in the admin panel, it shows up as 4TeBms2K 4TeBms2K: MyApp Profile (see that the __str__ method shows that that should be the ID instead of the user ID) Custom model that it's inheriting from def gen_uuid(length: int = 8): return base58.b58encode(uuid.uuid4().hex).decode('utf-8')[:length] class UUIDField(CharField): description = "Unique UUID primary key for model." def __init__(self, max_length=8, *args, **kwargs): super().__init__( primary_key=True, unique=True, max_length=max_length, editable=False, serialize=False, default=gen_uuid, ) class UUIDModel(Model): id = UUIDField() max_length = 8 class Meta: abstract = True def __init__(self, max_length=8, *args, **kwargs): self.max_length = 8 self.id = UUIDField(max_length=max_length) super().__init__(*args, **kwargs) def save(self, *args, **kwargs): saved … -
Two Widgets in one form for same fields are not working at the same time
I have build a BlogApp and I am working on Forms. BUT I want to add two Widgets in One Form and Both widgets are for one same Field. forms.py class EditBlogPost(forms.ModelForm): class Meta: model = BlogPost fields = ['title'] widgets = {'title':forms.TextInput(attrs={'placeholder': 'e.g. For Painting, For Sculpting'})} widgets = {'title' : forms.Textarea(attrs={'cols':30})} The Problem When i put TextInput widget right below fields instance then TextInput widget works in Browser page but Textarea doesn't work AND when i put Textarea widget below fields instance then Textarea works and TextInput doesn't work. BUT i want them to run both at same time. I don't know what to do. Any help would be Appreciated. Thank You in Advance -
Creating a website that can help other create playslists from external sites [closed]
I'm a beginner ato Django and web development. recently as more edTech startups are rising. I'm planning on making a site that enables users to create a playlist of free materials that they find useful. Like if the playlist can contain videos from youtube, khan academy etc.. I tried googling on how to make such sites but I found no way. Any resources on getting me started and suggestions? -
JSON Web Token no longer has 'decode' attribute despite no changes
I have a function which provides a token for a user so they can access a video chat room using the Twilio Video API. Following their docs, we decode a JSON Web Token with the following code to give us their token: token = AccessToken(ACCOUNT_SID, API_KEY, API_SECRET, identity=f'{request.user.email}') token.add_grant(VideoGrant(room='My Room')) context = { 'token': token.to_jwt().decode() } This worked perfectly locally, and upon pushing it to live servers, continued to work there without fault. However, a few pushes later, with no changes to this code, and this error (below) has suddenly occurred. This also comes at the same time as another error, which is an ascii encoding error, which I believe may be linked. It's strange that although no changes have been made to this token object, or the function, that we suddenly encounter this error with decoding this token. If anyone has any pointers, would be greatly appreciated. -
How to redirect from payment page to index page
After payment, I have redirected it to the success page. form action="success" method="POST" Views tab def success(request): return render(request, 'success.html') Now I want the page to automatically redirect to the index/home page after a small delay. How can that be achieved. Can anyone please help with this? -
Query set is not JSON serializable
I am trying to create an endpoint but I keep getting an error: "Object of type model is not JSON serializable". I tried passing it through list() and json.dumps() but it int work. I tried printing the query and it was like [<Lead: Test>, <Lead: user2>, <Lead: user3>, <Lead: user4>] Here is the code I wrote: def leads(request): full = [] lead_list = list(Lead.objects.all()) print(lead_list) for i in lead_list: full.append(json.dumps(i)) print(full) return JsonResponse(list(full), safe=False) Here are a few question I looked at and tried: Output Django queryset as JSON I tried serializing it with serializer but the response was like this: "[{\"model\": \"leads.lead\", \"pk\": 1, \"fields\": {\"first_name\": \"Test\", \"last_name\": \"User\", \"age\": 25, \"city\": \"kolkata\", \"country\": \"India\", \"email\": \"ankr@gmail.com\", \"agent\": 1, \"status\": \"Potential\"}}, {\"model\": \"leads.lead\", \"pk\": 2, \"fields\": {\"first_name\": \"user2\", \"last_name\": \"test2\", \"age\": 44, \"city\": \"Mumbai\", \"country\": \"India\", \"email\": \"test2@gmail.com\", \"agent\": null, \"status\": \"prospect\"}}, {\"model\": \"leads.lead\", \"pk\": 4, \"fields\": {\"first_name\": \"user3\", \"last_name\": \"test3\", \"age\": 19, \"city\": \"Paris\", \"country\": \"France\", \"email\": \"test3@gmail.com\", \"agent\": null, \"status\": \"Prospect\"}}, {\"model\": \"leads.lead\", \"pk\": 8, \"fields\": {\"first_name\": \"user4\", \"last_name\": \"test4\", \"age\": 33, \"city\": \"London\", \"country\": \"UK\", \"email\": \"test4@gmail.com\", \"agent\": null, \"status\": \"Converted\"}}]" -
How do i redirect url to my admin page or home page once the user signed up and try to login after that ? Help Appricated
I have created a login and logout form and able to create the user at the admin page with sign up. I want the user when he signed up and login should redirect the page. login.html {% load static %} {% block content %} {% load crispy_forms_tags %} <!--Login--> <html> <head> <title> login </title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> </head> <div class="container py-5"> <h1>Login</h1> <form method="POST"> {% csrf_token %} {{ login_form|crispy }} <button class="btn btn-primary" type="submit">Login</button> </form> <p class="text-center">Don't have an account? <a href="/register">Create an account</a>.</p> </div> </html> {% endblock %} register.html {% load static %} {% block content %} {% load crispy_forms_tags %} <!--Register--> <html> <head> <title> login </title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> </head> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form|crispy }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> </html> {% endblock %} views.py from django.shortcuts import render, redirect from .models import * from .forms import NewUserForm from django.contrib.auth import login, authenticate from django.contrib import messages #import messages from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm #add this # Create your views here. def homeView(request): views = … -
Error reading XMLStreamReader by django request
My xml data: xml_payload = <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <Authentication > <username>blabla</username> <password>123456789</password> </Authentication> </soap:Header> <soap:Body> <data> <title>Test title</title> <content>Test body format</content> </data> </soap:Body> </soap:Envelope> My request in django project: try: url = "http://someurls.com" res = requests.post(url=url, data=xml_payload, headers={'Content-type': 'application/xml'}) return response.content, response.status_code except Exception as e: print(e) return None, 500 When i hit the request using postman then i get response is given bellow: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <soap:Fault> <faultcode>soap:Client</faultcode> <faultstring>Error reading XMLStreamReader.</faultstring> </soap:Fault> </soap:Body> </soap:Envelope>' It returns an error. I am surfing around the internet but didn't find any answer which is fulfilled my query. -
I want Auto Select corresponding values of two Select2 dropdown for large data
Requirement :- Web-Framework - Django I have got the task from my company in which i have two Select2 dropdown let say X and Y respectively and i am loading the values of X and Y from the excel file using pandas library. problem is data size of the excel file is very large around 15k of records and they want a functionality of if anyone value of dropdown is selected then their corresponding value should also be selected automatically in the other select2 dropdown. When i load the data in bulk select2 dropdown is lagging to solve. Also client is demanding that they want to see options when he click to select2 dropdown before making any search. What i have tried :- this is my index.html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index2.html</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" /> <style> #id_language { width: 100%; } </style> </head> <body> <div class="container"> <h3>Select Anyone</h3> <br> <br> <select name="language" id="id_fragname" class="w-50"> <option value="-1">Select Fragrance</option> </select> </div> <br> <br> <div class="container"> <br> <br> <select name="language" id="id_fragcode" class="w-50"> <option value="-1">Select Code</option> </select> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <script> //put your jquery code here $(document).ready(function () … -
Getting user's IP after sign up
I have a Django Website and I'm using IPInfo. When the user signs up, I have the following signal: def create_profile(request, user, **kwargs): ip = request.ipinfo.ip city = request.ipinfo.city country = request.ipinfo.country region = request.ipinfo.region timezone = request.ipinfo.timezone postal = request.ipinfo.postal loc = request.ipinfo.loc //Save into DB However, instead of saving the user's details it saves the server's IP, city, etc. What am I doing wrong and how can I fix this? -
Xvfb-run as a subprocess in Django running xfreerdp fails
I have a ThreadPoolExecutor object(rdp_connector_global) in a Dockerized Django application's view method calling the below method(_rdp_connect) via submit as follows: rdp_connector_global.submit(_rdp_connect, login.ip_address, login.remote_port, login.username, login.password, login.rdp_width_pixels, login.rdp_height_pixels) def _rdp_connect(hostname_or_ip, port, username, password, rdp_width_pixels=1920, rdp_height_pixels=1080): domain = None username_simple = username if "\\" in username: split = username.split["\\"] domain = split[0] username_simple = split[1] elif "@" in username: split = username.split["@"] username_simple = split[0] domain = split[1] connection = None if domain is None: xvfb_args_str = "/usr/bin/xvfb-run /usr/bin/xfreerdp /sec:tls /u:{0} /p:{1} /w:{2} /h:{3} /v:{4}:{5} /cert-ignore".format(username_simple, password, rdp_width_pixels, rdp_height_pixels, hostname_or_ip, port) connection = subprocess.Popen(xvfb_args_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) else: xvfb_args_str = "/usr/bin/xvfb-run /usr/bin/xfreerdp /sec:tls /d:{0} /u:{1} /p:{2} /w:{3} /h:{4} /v:{5}:{6} /cert-ignore".format(domain, username_simple, password, rdp_width_pixels, rdp_height_pixels, hostname_or_ip, port) connection = subprocess.Popen(xvfb_args_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) logging.info(connection.communicate()) connection.wait() logging.info(connection.communicate()) Xvfb and freerdp are installed in the Docker container correctly. The login command succeeds when I run it from Django shell or the shell inside the Docker. But the same command fails to login to the remote Windows machine when running via code. I am wit's end to solve this, any help is appreciated! When running via Django I get a ERRINFO_LOGOFF_BY_USER after 30 seconds of unsuccessful wait to connect to Windows machine. -
How to show rendered template as raw source code block?
I want to provide a rendered HTML block that shows an email signature - what it looks like with user data from the context - and also displays the populated HTML code as raw src to be copied for pasting into customers email signature. What would be the best (dry) way to do this? I have tried render_to_string as a variable in the context but the HTML is rendered. -
Customising Admin Panel In Django
I am working on An Ecommerce website, in this I am using following model: ''' class Order(models.Model): user = models.ForeignKey(User) date = models.DateTimeField(auto_now_add=True) order_total = models.PostiveIntegerField(default=0) class OrderItem(models.Model): order = models.ForeignKey(Order) item_name = models.CharField(max_length=20) quantity = models.PositiveIntegerField(default=0) ''' Inside admin panel I want to show these ordered Items detail together which belongs to the same order id. How can I customise my modelAdmin in order to OrderItem details as a readonly_Field. -
TypeError at /datatable datatable() missing 1 required positional argument: 'file'
In views.py def datatable(request,file): csv_fp = open(f'csv_upload_files/{file}.csv', 'r') reader = csv.DictReader(csv_fp) headers = [col for col in reader.fieldnames] out = [row for row in reader] return render(request, 'result.html', {'data' : out, 'headers' : headers}) In urls.py urlpatterns = [ path('', views.upload,name='upload'), path('datatable',views.datatable,name='datatable') ] I am unable to understand how to provide the saved csv file to the function datatable -
Django Error: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
It gives the error: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('App.urls')), path('accounts/', include(('django.contrib.auth.urls', 'django.contrib.auth'), namespace='login')), path('accounts/', include('Account.urls')), ] index.html <a href="{% url 'login' %}"><h3 class="agileinfo_sign">Sign In </h3></a> -
ValueError: invalid literal for int() with base 10: 'testuser1-2'
I'm trying to allow users to delete their own comments. I received this error: ValueError: invalid literal for int() with base 10: 'testuser1-2 Any idea whats wrong with my code? html {% for comment in blog_post.comments.all %} <form action = "{% url 'HomeFeed:deletecomments' comment.post_id %}" method = "POST"> {% csrf_token %} <br> {{ comment.body }} <button>Delete</button> </form> {% endfor %} urls.py path('comments/<slug>', AddCommentView.as_view(), name= "add_comment"), path('deletecomments/<post_id>', delete_own_comment, name= "deletecomments"), views.py @login_required def delete_own_comment(request, post_id): if request.method == 'POST': comment = get_object_or_404(Comment, post_id=post_id) if comment.user == request.user: comment.delete() return redirect('HomeFeed:detail', slug=slug) models.py class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE) body = models.TextField() date_added = models.DateField(auto_now_add=True) class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) brief_description = models.TextField(max_length=300, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) -
UserCheckout matching query does not exist
I'm trying to display all orders matching each logged in user, I dont understand why it gives me issues when trying to filter for users as it gives me that UserCheckout does not have any matching queries: orders/views.py class OrderList(LoginRequiredMixin, ListView): queryset = Order.objects.all() def get_queryset(self): user_check_id = self.request.user.id user_checkout = UserCheckout.objects.get(id=user_check_id) return super(OrderList, self).get_queryset().filter(user=user_checkout) orders/mixins.py class LoginRequiredMixin(object): @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs) orders/models.py class UserCheckout(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete = models.CASCADE) # not required as to allow guests to checkout too email = models.EmailField(unique=True) # required, unique as if there the guest already has an authentication just one email needed def __str__(self): return self.email Error it gives me: DoesNotExist at /orders/ UserCheckout matching query does not exist. -
Django rest framework: load model data into serializer maually (to then send it as an HTTP payload / webhook)
So we have a post-save signal that calls a celery task that is using requests to notify one of our partners about an order by a user he has referred to us. I would like the payload to equal the detail view output of the order. So far so good. However, for test-ability purposes and also to avoid unnecessary HTTP calls, I would like to retrieve the instance from the DB (in the celery task), feed it to the serializer (OrderDetailSerializer) and then call requesst.post with serializer.data What is the easiest way to achieve that The closest question to this one I found is this Using Django rest framework as a rest client The answer suggested to use simple JSON serialization. However, it is not a good solution for us because the serializer hides some sensitive data and ads some nested data via NestedSerializers. -
python django logging: One single logger with more than one logging level
tl;dr: Is there any way to have one single logger that manages all loglevels? I am using the logging library on a certain django project. Django manages logging exactly the same as the regular logging library, but with the benefit that you can declare loggers, handlers, filters, etc. on a separate settings.py file. Currently, I have some loggers and handlers on my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers' : False, 'loggers': { 'info': { 'handlers' : ['std_err', 'info_logfile'], 'level': 'INFO', }, 'info.contract': { 'handlers': ['contract_info_logfile'], 'level': 'INFO', 'propagate': True, } }, 'handlers': { 'std_err': { 'class': 'logging.StreamHandler' }, 'info_logfile': { 'class': 'logging.FileHandler', 'filename': 'info.log', 'formatter': 'default', }, 'contract_info_logfile': { 'class': 'logging.FileHandler', 'filename': 'contract.info.log', 'formatter': 'default', } } 'formatters': { 'default': { 'format': '%(asctime)s [%(module)s] %(message)s', } } } In my code, I simply run: logger = logging.getLogger('info.contract') logger.info("Some info message...") Which prints 2021-01-24 03:05:02,063 [contract_generator] Some info message... to console. This works very well and is what I expect. The problem I am having is the following: In order to log to different files depending on the loglevel, I would have to create a new logger for each loglevel. Which is to say, the following doesn't work: logger = … -
Using Django, SimpleJWT checking User permission to show content belongs to his own company
I am using React(front), Django(server-side), Simple JWT for User Auth Model and Postgres DB. Let me explain my model: Company owns many properties, and each company has multiple users. As a user logs in, I want them to see a list of properties that belongs to their own company. As the user selects any property from the list, I need to again check if the user has permission and then run the queries. I am currently using Simple JWT for authentication. As the user logs in, the backend generates Access and Refresh tokens. With every request sent from the user side, I am sending JWT access token. On the server side, I want to decode the token, look at what company user belongs to, filter queries accordingly and send the JsonResponse. Here is my Company Model: class Company(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='company_user', on_delete=models.CASCADE, null=True) company_name = models.CharField(max_length=200, null=True) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ['name'] def __str__(self): return self.name Here is the property model: class Property(models.Model): company = models.ForeignKey(Company, related_name='prop_company', null = True, on_delete=models.CASCADE) property_name = models.CharField(max_length=200, null=True) property_type = models.CharField(max_length=200, null=True) def __str__(self): return self.property_name Here is the property data class PropertyData(models.Model): data = models.ForeignKey(Property, related_name='property_data', null … -
Updating database on Django
Good day SO. I want to ask something basic. I tried on my end to update my data from html to save to database but to no avail. My Model structure is Account extends to AbstractBaseUser, BaseUserManager and CompanyAccount links to Account by OneToOneField. I can say that my Model should have no problem since I can Register Account and Company Account without any problems. views.py @login_required(login_url='/login/') def user_my_page(request, *args, **kwargs): context = {} context['form_type'] = 'update' context['account_type'] = request.user.account_type if request.POST: if request.user.account_type == 1: company = CompanyAccount.objects.get(account=request.user) account_form = CompanyAccountForm(request.POST, instance=request.user) if account_form.is_valid(): account_form.save() print(request.POST) print('SAVE') else: print('ERROR') forms.py class AccountCreationForm(UserCreationForm): accuser_id = forms.CharField(max_length=10, help_text="Required") class Meta: model = Account fields = ("accuser_id", "password1", "password2") class CompanyAccountForm(forms.ModelForm): class Meta: model = CompanyAccount fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['company_name'].widget.attrs.update({'class': 'content-input'}) self.fields['company_name_kana'].widget.attrs.update({'class': 'content-input'}) print(request.POST) <QueryDict: {'csrfmiddlewaretoken': ['6zrwt68PNiJKrgZcKanDcVJkqAtogbQbNk2wHwjOzg7ybfq3Lyei9ZqdbmAJcYrV'], 'company_name': ['TESTING'], ....etc This part here, it does print SAVE on my terminal but it does not save to the database. -
django is m2m relationship really necessary?
So I have two models like this. class Channel(BaseModel): class Meta: verbose_name = 'channel' verbose_name_plural = 'channels' indexes = [ models.Index(fields=['box', 'name'], name='channel_box_name_idx'), ] def __str__(self): return self.name def get_next_position(self): aggregate = self.box.channels.aggregate(models.Max('position')) return (aggregate['position__max'] or -1) + 1 def save(self, *args, **kwargs): if self._state.adding: # we insert the object's position if # it hasn't been created yet. We need to do # this explicitly because django doesn't # allow more than one auto-field self.position = self.get_next_position() super(Channel, self).save(*args, **kwargs) return self.box.channels.add(self) super(Channel, self).save(*args, **kwargs) objects = models.Manager() name = models.CharField(max_length=100, validators=[MinLengthValidator(2)]) box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE) position = models.PositiveSmallIntegerField(db_index=True) REQUIRED_FIELDS = [name, box] class Box(BaseModel): class Meta: verbose_name = 'box' verbose_name_plural = 'boxes' indexes = [ models.Index(fields=['owner'], name='box_owner_idx'), models.Index(fields=['owner', 'name'], name='box_name_owner_idx'), ] def __str__(self): return self.name objects = models.Manager() icon = models.ImageField(upload_to='icons/', storage=DefaultStorage) name = models.CharField(max_length=100, validators=[MinLengthValidator(2)]) owner = models.ForeignKey('api_backend.User', on_delete=models.CASCADE) channels = models.ManyToManyField('api_backend.Channel', related_name='box_channels') REQUIRED_FIELDS = [name, owner] Channel has an attribute box. And box has a m2m field channels. so in this type of relationship, whenever I create the channel with the box, I need to add the same to the box's m2m field channels. Is something like this really necessary? Like I need to have an extra … -
How do I add what I have written in my forms.py into views.py
Hi I have written a function in my forms.py to check to make sure that if a the form submitted has a slug or title that is the same as a blog post created before, they will return a message saying that the title already exists. How do I include this in my views.py so that it will work in the template? or did I write my function in forms.py wrongly? because the form isnt valid now. Note: There is no slug field in my form. The slug is only for the url..thank you! views.py def create_blog_view(request): context = {} form = CreateBlogPostForm(request.POST or None, request.FILES or None) if form.is_valid(): obj= form.save(commit = False) author = Account.objects.filter(email=user.email).first() obj.author = author obj.save() obj.members.add(request.user) return redirect('HomeFeed:main') context['form'] = form return render(request, "HomeFeed/create_blog.html", {}) forms.py class CreateBlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['chief_title', 'brief_description'] BlogPost.objects.exclude(pk=self.instance.pk).filter(chief_title__iexact=chief_title): def clean_slug(self): slug = slugify(self.cleaned_data.get("chief_title")) if len(self.cleaned_data.get("slug", )) == 0 \ else self.cleaned_data.get("slug", ) if BlogPost.objects.filter(slug=slug).exists(): self.add_error("slug", "BlogPost with the same title/slug already exists") return slug html <label for="id_title">Chief Title!</label> <input class="form-control" type="text" name="chief_title" id="id_title" placeholder="Title" required autofocus> </div> {{form.chief_title.errors}} -
How to send url as slug field into url in Django
I have my urls.py as this: from django.urls import path from . import views urlpatterns = [ path('link',views.get_text,name='text'), path('link/<link>',views.show,name='show') ] When I enter a url like http://127.0.0.1:8000/link/https://www.geeksforgeeks.org/gate-cs-notes-gq/, it is showing page not found as it is checking the / in the slug url. I am storing the url and other fields in database, so I want to retrieve the database objects using the url. How to do such that when I enter a url in the browser, it takes the entire url as link field in urls.py , so that I can retrieve the db objects from views.py in this way: def show(request,link): objs = Links.objects.filter(link=link).values() return HttpResponse('link') -
Wagtail adding childpage directory before static paths in base.html
I have a project set up with the following models.py file: """Flexible page.""" from django.db import models from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page from wagtail.core.fields import RichTextField class FlexPage(Page): """Flexibile page class.""" template = "flex/flex_page.html" # @todo add streamfields # content = StreamField() subtitle = models.CharField(max_length=100, null=True, blank=True) Flexbody = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel("subtitle"), FieldPanel('Flexbody', classname="full"), ] class Meta: # noqa verbose_name = "Flex Page" verbose_name_plural = "Flex Pages" I also have a "base.html" that has static paths like: <link rel="stylesheet" id="main-css" href="./static/SiteFiles/main.css" type="text/css" media="all"> <link rel="stylesheet" id="tether-css" href="./static/SiteFiles/Sitetether.css" type="text/css" media="all"> <link rel="stylesheet" id="bootstrap-css" href="./static/SiteFiles/bootstrap.min.css" type="text/css" media="all"> <link rel="stylesheet" id="font-awesome-css" href="./static/SiteFiles/font-awesome.css" type="text/css" media="all"> On the homepage, I'm able to get everything to load properly, but when I create a flexpage, I get the following error: [23/Jan/2021 21:07:44] "GET /getting-started/static/SiteFiles/Sitetether.css HTTP/1.1" 404 3333 Not Found: /getting-started/.static/SiteFiles/wp-emoji-release.min.js.download It seems like when I try to extend the "base.html" file, within the child pages, that it is adding a directory to my paths. I'm not sure how to override this behavior.