Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with django 3.1, gunicorn : ModuleNotFoundError: No module named 'debates' - ubuntu 20.04 - digitalocean
I have the following problem following this tutorial, get to: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20 -04 # creating-systemd-socket-and-service-files-for-gunicorn, when checking the status of gunicorn the following error appears when reviewing the journal: Aug 26 02:17:12 web-debates gunicorn[23045]: ModuleNotFoundError: No module named 'debates' Aug 26 02:17:12 web-debates gunicorn[23045]: [2020-08-26 02:17:12 +0000] [23045] [INFO] Worker exiting (pid: 23045) Aug 26 02:17:12 web-debates gunicorn[23032]: Traceback (most recent call last): Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 202, in run Aug 26 02:17:12 web-debates gunicorn[23032]: self.manage_workers() Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 545, in manage_workers Aug 26 02:17:12 web-debates gunicorn[23032]: self.spawn_workers() Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 617, in spawn_workers Aug 26 02:17:12 web-debates gunicorn[23032]: time.sleep(0.1 * random.random()) Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Aug 26 02:17:12 web-debates gunicorn[23032]: self.reap_workers() Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Aug 26 02:17:12 web-debates gunicorn[23032]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Aug 26 02:17:12 web-debates gunicorn[23032]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Aug 26 02:17:12 web-debates gunicorn[23032]: During handling of the above exception, another exception occurred: Aug 26 02:17:12 web-debates gunicorn[23032]: Traceback (most recent call last): Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/bin/gunicorn", line 8, in <module> Aug 26 … -
how do I setup a lesson allow to have more than one permission based on my column membership_id?
I am trying to code a single course platform where each lesson could have more than one permission based on the membership_id, so this field can have 1,2 or any it means free or both(free and paid). my code works fine as it only takes one perm, but as I cannot add another perm or change the permit will strictly use that one. so I want to allow 1 to many status def get(self, request): lesson = get_object_or_404(Lesson, pk=8) user_membership = UserMembership.objects.filter(user=self.request.user).first() user_membership_type = user_membership.membership.membership_type print(user_membership_type) lesson_allowed_mem_types = lesson.allowed_memberships.all() allowed_memberships.set(Mebership.objects.all()) context = { 'lesson': None , [..]} if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists(): # user is member context = { 'lesson': lesson} # not a member return render(request, "xxxxxxxxxxxx.html", context) models class Lesson(models.Model): [..] allowed_memberships = models.ManyToManyField(Membership) def __str__(self): return self.content_title class Meta: ordering = ['pk'] MEMBERSHIP_CHOICES = ( ('Free', 'free'), ('Professional', 'pro'), ) class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) [...] def __str__(self): return self.membership_type class UserMembership(models.Model): [..] membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.email database id,lesson_id,membership_id "2" "2" "2" "8" "8" "2" "9" "1" "2" "10" "3" "2" "11" "4" "2" "12" "5" "2" "13" "6" "2" "14" "7" "2" each lesson can have more than one permission example. … -
Anyone django genius here? How to connect excel file in my project?
I spent 2 night to solve this ploblem... My first question in stackoverflow In views.py def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('../../analysis') else: form = UploadFileForm() return render( request, 'blog/upload.html', {'form': form} ) In models.py class UploadFileModel(models.Model): title = models.TextField(default='') file = models.FileField(null=True) I implemented excel,csv file's uploading in my website. And file is saved in '_media' folder. I want to execute machine running code with this excel file. How can i get name of uploaded file? Plz... -
django.db.utils.OperationalError: no such column: tickets_ticket_notes.ticket_id
I am getting this error on when I try to create a note or comment section to a post. I am trying to make kind of a ticketing system and if I remove the section where it looks for existing comments/notes it works fine. I feel as if I am missing a connection to the tickets/post from the notes/comments. I have a the notes linked to the tickets by a foreign key in my models. not sure what else I am missing. django.db.utils.OperationalError: no such column: tickets_ticket_notes.ticket_id Models.py class Tickets(models.Model): STATUS = ( ('Assigned', "Assigned"), ('Traveling', "Travelling"), ('Completed', "Completed"), ('On Hol', "On Hold"), ) assigned_tech = models.ForeignKey('auth.User', on_delete=models.CASCADE, null=False,) ticket_number = models.CharField(max_length=10) SM_number = models.CharField(max_length=14, default="service manager number") slug = models.SlugField() status = models.CharField(max_length= 10, choices=STATUS, default='Assigned') due_date = models.DateTimeField(datetime.date.today()) summary = models.CharField(max_length=60, null=False, default="Must Change") asset_tag = models.CharField(max_length=10) address = models.TextField(max_length=30, default='enter address') city_state = models.CharField(max_length=14, default='enter city/state') description = models.TextField(default='enter ticket description') def get_absolute_url(self): return reverse('ticket_detail', kwargs={'slug': self.slug}) def __str__(self): return self.ticket_number class Ticket_Notes(models.Model): TYPE = ( (0, "On Site"), (1, "Travelling"), ) user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null=False) ticket = models.ForeignKey(Tickets, on_delete=models.CASCADE, related_name='notes') note =models.TextField(blank=True) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(auto_now_add=True) entry_type = models.IntegerField(choices=TYPE, default=0) created_on = models.DateTimeField(auto_now_add=True) … -
Django error - __str__ returned non-string (type User)
I have the below 2 models - User and PhoneProfile. I can successfully create records for User. When i browse to PhoneProfile using admin console, i can see the foreign key present. On selection of an entry and completion of the rest of the fields, i get the error below. class User(AbstractBaseUser): phone_regex = RegexValidator(regex = r'^\+?1?\d{2,14}$', message = "Phone number must be in the format: '+xxxxxxxxxx'.") phone = models.CharField(validators = [phone_regex], max_length = 15, unique = True) first_name = models.CharField(max_length = 50, blank = False, null = False) last_name = models.CharField(max_length = 50, blank = False, null = False) email = models.CharField(max_length = 100, blank = True, null = True) first_login = models.BooleanField(default = False) active = models.BooleanField(default = True) staff = models.BooleanField(default = True) admin = models.BooleanField(default = False) timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] objects = UserManager() class PhoneProfile(models.Model): registered_phone = models.ForeignKey(User, on_delete=models.CASCADE, related_name='registered_phone') notify_enable_low_bal = models.BooleanField() notify_amount_low_bal = models.DecimalField(decimal_places=2, max_digits=10000, default='50', null=True) Error message when i attempt to create an entry in PhoneProfile model __str__ returned non-string (type User) Request Method: POST Request URL: http://localhost:8000/admin/smartrecharge/phoneprofile/add/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: __str__ returned non-string (type User) Exception Location: /Users/django-backend/venv/lib/python3.7/site-packages/django/contrib/admin/options.py in log_addition, … -
Blank options in space tag
Hello I have a model in Django where I have a forein key and I am displaying it with a select tag in html. However there are blank options in the selector tag but not in my database. How can I remove them. I want also to ask how I can delete the ------ option. html, only the select tag <select style='width:200px';name="bolum" required="" id="id_bolum"> {% for x in form.bolum %} {% if {{x}} ''%} {%else%} <option value="{{x.id}}">{{x}}</option> {% endif %} {% endfor %} </select> models.py from django.db import models # Create your models here. class Department(models.Model): department=models.CharField(max_length=128) def __str__(self): return self.department class WPGroup(models.Model): bolum = models.ForeignKey('Department', on_delete=models.CASCADE, related_name='department_for_wpgroup',null=False, blank=False) name=models.CharField(max_length=128,blank=False) number=models.PositiveIntegerField(blank=False) mail=models.EmailField(max_length=128,blank=False) def __str__(self): return self.name forms.py from django import forms from .models import WPGroup class WPGroupForm(forms.ModelForm): class Meta: model=WPGroup fields=['name','number','bolum','mail'] def clean_mail(self): email = self.cleaned_data['mail'] if "@itu.edu.tr" not in email: raise forms.ValidationError("You must include @itu.edu.tr") return email here is also a screenshot of the website -
django chart.js - Query to get count of all distinct values for particular column
My goal is to create a query to group together unique 'charges' and count them. Then correctly implementing a for loop, which would in a pie chart showing multiple slices, each individual slice showing the total count per unique charge. My problem is using my current queries I run into the following attribute error 'dict' object has no attribute 'charge'. I have tried a few different ways to write the query and would appreciate feedback in writing a query or in my for loop. # Models.py class Arrest(models.Model): number = models.IntegerField() date = models.DateField() charge = models.CharField(max_length=64) # Views.py def visuals(request): data = [] labels = [] # The two queries I have tried. # queryset = Arrest.objects.values('charge').annotate(the_count=Count('charge')) # queryset = Arrest.objects.values('charge').order_by('charge').annotate(the_count=Count('charge')) for arrest in queryset: data.append(arrest.charge) labels.append(arrest.charge) return render(request, "data/visuals.html", { 'labels': labels, 'data': data, }) # Error AttributeError at /visuals 'dict' object has no attribute 'charge' -
How do I assign instances to models in django?
I'm building a child chore management app, and I've run into a blocker. Here's what I'm trying to do: assign individual kids individual instances of various rules (i.e. having multiple instances of "wash dishes", so that one kid can complete their version without it being marked as complete for each kid), so I will be able to: only display the rules that are assigned to each kid on their own page (i.e. kid 1 can have their instances of rules a, b, c displayed, while kid 2 has their instances of rules b, c, d displayed) end goal is to be able to tally up the points each kid has earned Here's what I have done so far: displaying list of all kids ability to create rules instances displaying all rules instances with every child. Here are my models: class Rule(models.Model): """ Model representing a base class for rules. Weight field is how much you want the rule to be worth. The same rule can be applied to multiple kids, and a single kid can be assigned multiple rules. """ name = models.CharField(max_length=50, help_text='Enter rule', default=None) weight = models.IntegerField(default=0) description = models.TextField(max_length=250, help_text='Enter description of rule') completed = models.BooleanField(default=False, help_text='Is … -
How can I create a model property based on specific model fields?
Let's say I have the following model: class DriverReview(models.Model): driver = models.ForeignKey(Driver, on_delete=models.CASCADE,) driving_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)]) communication_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)]) professionalism_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)]) review_text = models.TextField() created = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name="driver_review_created_by", on_delete=models.CASCADE, null=True, blank=True) last_updated = models.DateTimeField(auto_now=True) last_updated_by = models.ForeignKey(User, related_name="driver_review_last_updated_by", on_delete=models.CASCADE, null=True, blank=True) is_deleted = models.BooleanField(default=False) deleted = models.DateTimeField(null=True, blank=True) deleted_by = models.ForeignKey(User, related_name="driver_review_deleted_by", on_delete=models.CASCADE, null=True, blank=True) @property def review_average_score(self): review_average_score = round(np.mean([self.driving_score, self.communication_score, self.professionalism_score]), 2) return review_average_score I have created a property to get the review average score. The issue is that I don't want to hardcode the _score fields. Is there a way to filter the fields that contain _score and use them in the average ? -
Conditionally showing a button with DJANGO template language
I have a page that should show a button if the user is marked as "facturable" (billable), otherwise, the button should not appear. I tried the following code: {% if form_experfil.facturable %} <a href="{% url 'incid:xtodo' %}?pagref=factdatshow" type="button" class="btn btn-primary waves-effect"> Consultar datos de facturación</a> {% endif %} But it keeps showing. This and other fails make me think that the {% if %} tag behaviour isnh't as straightforward as I thought, and it does not just clip the html code down to the endif tag, but something gets rendered first. Is there somewhere where this is formally documented without mystical references?. Is there a way to just show this button when the customer has this data and not show it otherwise?. -
Django w/django_filters lookups by methods or non-model fields
Versions: Django 3.0.6, Python 3.8, MySQL 8.0, django_filters 2.3.0 Please bear with me as I am not sure if I have entitled the question properly. I will start with the relevant code: ========= models.py ========= class Vendor(models.Model): name = models.CharField(max_length=50) class Category(models.Model): name = models.CharField(max_length=50) class Product(models.Model): name = models.CharField(max_length=50) vendor = models.ForeignKey('Vendor', on_delete=models.SET_NULL, null=True) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) class Rating (models.Model): score = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10)]) product = models.ForeignKey('Vendor', on_delete=models.SET_NULL, null=True) def category(self): return self.product.category def vendor(self): return self.product.vendor ========== filters.py ========== from .models import Vendor, Category, Product, Rating import django_filters class RatingFilter(django_filters.FilterSet): rating_filter = django_filters.RAngeFilter(field_name='score', lookup_expr='range') class Meta: model = Rating fields = '__all__' ======== views.py ======== from .filters import RatingFilter def RatingSearch(request): rating_list=Rating.objects.all() rating_filter = RatingFilter(request.GET, queryset=rating_list) return render (request, 'inventory/rating_search.html', { 'filter': rating_filter}) From a basic SQL perspective, I know that I can use the models as outline and filter a search of Rating records by a Category or Vendor by establishing the relationships between the tables. My goal is to use django_filters to do the same thing on a web form. Out of the box it is super easy to filter Ratings by Product and/or the Score. What I can't seem to sort out is … -
How can I extend django-admin
I have been looking for a way to extend the default django admin so that it can be showing User KPI's like Total Users any suggestions? Instead would it be proper to just create a separate view for that without tampering the default admin -
Django does not recognize column on annotated queryset when using queryset.values_list
I'm struggling with a very painful problem, regarding the usage of annotated in querysets and the usage of the function values_list. Here is the thing, in one of my core apps, i have a manager.py, that i use to implements some verbosity operation: class ProcedureManager(InheritanceManager): def get_queryset(self): core_models = importlib.import_module('core.models') queryset = super(ProcedureManager, self).get_queryset().select_subclasses() return queryset.annotate( total=Coalesce( Count('images__marks'), 0 ), total_images_count=Coalesce( Count('images'), 0 ), processed_images_count=Coalesce( Count('images', filter=models.Q(images__status=True)), 0 ), status=models.Case( models.When(processed_images_count__gt=0, then=True), default=False, output_field=models.BooleanField() ), positive=Exists( core_models.ImageMark.objects.filter( pattern__positive=True, image__procedure__pk=OuterRef('pk') ) ), suggested=Exists( core_models.ImageMark.objects.filter( suggested_pattern__positive=True, image__procedure__pk=OuterRef('pk') ) ) ) this class is used inside one of my models in models.py class Procedure(models.Model): objects = ProcedureManager() city = models.ForeignKey('accounts.City', on_delete=models.CASCADE) type = models.ForeignKey('core.ProcedureType', on_delete=models.CASCADE) company = models.ForeignKey( 'accounts.Company', related_name='procedures', on_delete=models.CASCADE) ...... def mark_result(self): if self.pk is None: return {} lookup = 'images__marks__pattern__name' queryset = Procedure.objects.filter(pk=1954) data = queryset.values_list(lookup, models.Count(lookup)) return {pattern: count for pattern, count in data if pattern is not None} def get_suggested_patterns(self): if self.pk is None: return {} lookup = 'images__marks__suggested_pattern__name' queryset = Procedure.objects.filter(pk=self.pk) data = queryset.values_list(lookup, models.Count(lookup)) return {suggested: count for suggested, count in data if suggested is not None} I have some template tags that I use in my templates html as follows: @register.simple_tag def build_positive_tooltip(procedure): result = … -
Django REST Upload CSV return Response with All posts
I have a Blog CMS that's working great, but I want to be able to upload a CSV with multiple test posts, and then add them to the database all at once. Right now I can upload the CSV and iterate through the lines, but because my POST functions returns a Response, it quits after one iteration. How can I get it to iterate through all the lines and then return the list of created Blog Posts? Here is my code that works to create one at a time: class PostsImportAPIView(generics.ListCreateAPIView): serializer_class = DashboardPostSerializer permission_classes = [IsOwner] pagination_class = BlogPostPagination def get_queryset(self, *args, **kwargs): return BlogPost.objects.all() def post(self, request, *args, **kwargs): if request.FILES: data = request.data else: data = request.data.copy() csv_file = TextIOWrapper(data['csv'].file, encoding='ascii', errors='replace') import_csv = csv.reader(csv_file) next(import_csv) counter = 0 for line in import_csv: if line: data['title'] = line[0] data['body'] = line[1] date_field = line[2].split('+') data['created_at'] = datetime.datetime.strptime(date_field[0], '%Y-%m-%d %H:%M:%S.%f') data['published'] = line[3] serializer = DashboardPostImportSerializer(data=data, context={'request': request}) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This works greater for one at a time, but what I'd like to do is increment my counter for each completed row, then return a queryset of posts that match the … -
floatformat causes data not to render
I am trying to use the built in filter floatformat to format my data but its just causing it not to render. I can print the data fine using {{ form.field }} but when I add {{ form.field|floatformat:2 }} the data does not render. I thought it might be from the fact I a passing it to my template as a dictionary and therefor it's treating my data as a string which could cause some errors but I am not completely sure how to check that or if that is even the problem. -
App label over-riding an earlier app label
How can I assign a Django app, a label (e.g. auth) to over-ride an earlier application? The django.contrib.auth.… modules claim the app label auth. I want to have that installed, but claim the auth label for my site's custom auth app. -
Django URL tag makes variable suddenly be empty?
Weird puzzling problem. In my Django template, I can display a variable using {{item.slug}} and it's just fine. But, when I use that same variable in a URL tag, it's an empty variable. for example... <a href="{{item.slug}}">{{item.name}}</a> ...that works. <a href="{%url 'charts:ye_songs' start|date:"Y" 'r' 'label' item.slug %}">{{item.name}}</a> ...but that results in an error because item.slug is an empty string. I'm bamboozled what could be causing that. At first I thought it was 'cause I was using UTF-8 slugs, but that can't be the issue 'cause it does this with regular ol' Latin-1 ASCII characters too. If I hard code the variable, it works whether I use ASCII or UTF-8 characters. Also, this only occurs in this section of code. Other url tags aren't having this issue. Even the url's using the 'charts:ye_songs' are working as expected. I also tried using item.name where I'm using the slug. That displays the var string. My url.py path for this link looks like this... path('<int:chartyear>/<slug:sor>/<str:chart_type>/<str:slug>', views.ye_songs, name='ye_songs'), ...and that works for everything using this except for this particular bit. If I change the <str:slug> to <slug:slug>, then the variable string shows up but it results in a new error that affects all the links … -
What is the best way to upload a django project to cPanel?
I am trying to figure out an easy way to upload a django project to cPanel. Is there a way to do it with gitHub? I know how to make a python app, but I do not want to rebuild the whole thing. How can I upload an entire project? -
"Requested setting INSTALLED_APPS, but settings are not configured" error
getting this error in django project any ideas? File "C:\Users\Israel\PycharmProjects\defi\venv\lib\site-packages\django\conf_init_.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [screenshot][1] [1]: https://i.stack.imgur.com/vnyqW.png -
VCSNotInstalled: 'git' is not installed error with cookiecutter, but git is installed
I've been trying to create a project using cookiecutter but for some reason it doesn't identify my git installation. I'm running on Windows 10 and the installation was done with GitHub Desktop. (everycheese) C:\Django>cookiecutter gh:roygreenfeld/django-crash-starter Traceback (most recent call last): File "C:\Users\user\.conda\envs\everycheese\Scripts\cookiecutter-script.py", line 9, in <module> sys.exit(main()) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\click\core.py", line 829, in __call__ return self.main(*args, **kwargs) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\click\core.py", line 782, in main rv = self.invoke(ctx) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\click\core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\click\core.py", line 610, in invoke return callback(*args, **kwargs) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\cookiecutter\cli.py", line 140, in main cookiecutter( File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\cookiecutter\main.py", line 67, in cookiecutter repo_dir, cleanup = determine_repo_dir( File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\cookiecutter\repository.py", line 110, in determine_repo_dir cloned_repo = clone( File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\cookiecutter\vcs.py", line 84, in clone raise VCSNotInstalled(msg) cookiecutter.exceptions.VCSNotInstalled: 'git' is not installed. Nevertheless, when I run git from the Command Prompt it recognizes the command. Any ideas why cookiecutter might not be recognizing my git installation? -
Different rendering of same template with different views
I'm having a weird behaviour on my Django (3.0.3) site that is driving me mad. I have a CreateView and an UpdateView for my blog posts; both use the same post_form template, that extends from the base one. The problem is that when creating a new post my page is shown correctly, while when editing a post the styling is ignored! I'm completely lost... any help or direction to look at would be greatly appreciated. views.py ... class EditPost(LoginRequiredMixin, UpdateView): login_url = 'blog:login' model = Post form_class = PostForm class NewPost(LoginRequiredMixin, CreateView): login_url = "blog:login" model = Post form_class = PostForm def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.authorInfo = self.request.user.get_full_name() self.object.save() return redirect(self.get_success_url()) ... post_form.html {% extends "base.html" %} {% block title %} {% if form.instance.pk %} Edit post {% else %} Create post {% endif %} - {% endblock %} {% block content %} <div id="journal"> <div id="content"> {% if form.instance.pk %} <h2>Edit post</h2> {% else %} <h2>New post</h2><br> {% endif %} <form class="post-form" method="POST"> {% csrf_token %} {% for field in form %} <br> <p>{{field.label_tag}}{{field}}</p> {% endfor %} <button id="formButton" class="btn" type="submit">Save post</button> </form> </div> </div> {% endblock %} -
Page not found (404) Request Method: GET Request URL: http://localhost:8000/edit [closed]
Wondering if someone can help with an issue I'm having with an error message I received on my code. enter image description here Below is my urls.py enter image description here below is my views.py enter image description here and below is my html enter image description here -
DRF How to duplicate make duplicate of related FK
My models class Inspection(models.Model): user = models.ForeignKey(User, related_name="inspection", on_delete=models.CASCADE, blank=True, null=True) inspection_name = models.CharField(max_length=255) is_done = models.BooleanField(default=False) class Category(models.Model): inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE, related_name="categories") category_name = models.CharField(max_length=255) is_done = models.BooleanField(default=False) class Task(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='tasks') task_name = models.CharField(max_length=255) photo = models.FileField(upload_to="upload/task_photo", blank=True, null=True) text = models.CharField(max_length=355) is_done = models.BooleanField(default=False) contact_info = models.CharField(max_length=100) Question is how can I create duplicate of this 3models on POST request?? Any suggestions? -
Django reputation / like system for public user profile - error 404
I hope you're well :) I'm beginning with Django. I try to use a like system for the public profile of my users. But I don't understand why I got an error 404. Do you think it's possible to use PK with OneToOneField for user? user/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) reputation = models.ManyToManyField(User, related_name='user_reputation') ... user/views.py # public profile reputation @login_required(login_url='/earlycooker/login') def ReputationView(request, pk): userprofile = get_object_or_404(UserProfile, id=pk) if request.method == "POST": userprofile.reputation.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @property def total_reputation(self): return self.reputation.count() user/urls.py path('reputation/<int:pk>/', ReputationView, name="reputation_public"), user/templates/user_public_profile.html <form action="{% url 'user:reputation_public' user.pk %}" method="POST">{% csrf_token %} <button type="submit" name="user_id" value="{{ user.id }}" style=""><img src="/static/img/like.png" width="20px" height="20px" class="" style="border-radius: 90px;background: #ffffff36;" title=""> {{current_user.userprofile.total_reputation}} cherries</button> </form> Thanks a lot for your help, -
Default the value of an external key in a form
In the form for adding a calendar (of the Model "Calendar"), in the "group" field shows a drop-down menu where all the "CalendarGroups" are. I would like this menu not to be there and "group" to be set by default with the "group" id which I pass through the url parameter ("group_id"). How could I solve this? In models.py: class CalendarGroups(models.Model): name = models.CharField(max_length = 155, blank=True, null=True, unique=True) def __str__(self): return str(self.name) @property def get_html_url(self): url = reverse('', args=(self.id,)) return f'<a href="{url}"> {self.name} </a>' class Calendar(models.Model): name = models.CharField(max_length=200, unique=True) #created_by group = models.ForeignKey(CalendarGroups, on_delete = models.CASCADE, default='') @property def get_html_url(self): url = reverse('cal:calendar_view', args=(self.id, self.group)) return f'<a href="{url}"> {self.name} </a>' In forms.py: class CalendarGroupsForm(ModelForm): class Meta: model = CalendarGroups fields = ('name',) def __init__(self, *args, **kwargs): super(CalendarGroupsForm, self).__init__(*args, **kwargs) class CalendarForm(ModelForm): class Meta: model = Calendar fields = ('name', 'group') def __init__(self, *args, **kwargs): super(CalendarForm, self).__init__(*args, **kwargs) In views.py: def group(request, group_id=None): instance = CalendarGroups() if group_id: instance = get_object_or_404(CalendarGroups, pk=group_id) else: instance = CalendarGroups() form = CalendarGroupsForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:home')) return render(request, 'cal/form.html', {'form': form}) def calendar(request, group_id=None): instance = Calendar() form = CalendarForm(request.POST or None, instance=instance) if request.POST and …