Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SweetAlert2 implementation in django
My problem is that I need to do a click on the button that address you to an url that has an int:pk I don't know about javascript and I don't know how to do the redirect when I click, I was searching and I didn't find a way to do it with an int:pk HTML code <button onclick="sweet();"> Delete Student </button> VIEWS.PY CODE def delete_student(request, pk, template_name="main/delete_student.html"): student = get_object_or_404( Student , pk = pk ) student.delete() return redirect("index") return render(request, template_name, {"student": student}) JS code (SWEETALERT2) function sweet(){ Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value == False){ } if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted.', 'success' )})} -
Facing Issue With Django Machina Templates
I am Working on Rating Professor Website Using Django Framework.So That's Why I am Using Machina Forum But Facing Templates Issue In Settings .Loaders Are Not Working 'APP_DIRS': True, But When I Change 'APP_DIRS': False ,And Add MACHINA_MAIN_TEMPLATE_DIR To Templates Directory Machina Website Forum Works Fine But My Actual Website Goes Off Because of No Templates Exits Error. Question is That Can i Use Both Machina And My Template Directory at Same time And how ? If I add Machina Templates to Pycharm Project Templates and Make them as Templates then it's Work Or not ? There is Only Issue With Machina Templates Everything is Working Excellent . I Just Wanted Both Templates to Work On My Website . Setting.py import os from machina import MACHINA_MAIN_TEMPLATE_DIR from machina import MACHINA_MAIN_STATIC_DIR # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'djangoproject.apps.DjangoprojectConfig', … -
Django: Getting 404 Error After Adding Views, Models and URLs Correctly
I am a beginner in Django. Right now, I am doing a simple app, called GameReview. It will allow the users to add the reviews of their favorite games. Right now, I am facing a 404 error. It looks like this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/gamereview/ Using the URLconf defined in gamerevs.urls, Django tried these URL patterns, in this order: admin/ [name='hw'] gamereview [name='gamelist'] The current path, gamereview/, didn't match any of these. Here are my codes of models.py inside gamereview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tag(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tag) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = models.DateField(auto_now=True) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.review def save(self): super(Review, self).save() self.slug = '%i-%s' % ( self.id, slugify(self.game.title) ) super(Review, self).save() Here are my codes of urls.py inside gamereview folder: from . import views from django.urls import path urlpatterns = [ path('gamereview', views.gamelist, name='gamelist'), ] Here … -
Best practice to insure the connection and response from external API results
I have this code in python (using django firmware) that connects to an external API and update some values in that service. Each step depends on the previous step (for step 2 to work step 1 must return True and so forth that include a valid connection to the API). How can I insure that all of these steps takes place at the same time and if a single step fails how can I rollback and run all them at once in another try. here is the code. note that each class method do something in that external service. # 1. add new value to account if cls.add_balance(subscription_code, increase_amount): # 2. set new base balance if cls.set_topup_reset_action( subscription_code, new_base_balance, ): # 3. renew filters new_base_balance_20_percent = math.floor((Decimal( new_base_balance) * Decimal(20)) / Decimal(100)) if cls.set_filter_80_percent( subscription_code, new_base_balance_20_percent, ) and cls.set_filter_100_percent( subscription_code, ): # 4. renew thresholds if cls.set_threshold_profile_80_percent( subscription_code, ) and cls.set_threshold_profile_100_percent( subscription_code, ): return True return False -
creating custom or modified url using router for retrive method of ModelViewSet
I want to create a custom or modified url using router for ModelViewSet. Current scenario: /models.py class BlogPost(models.Model): title = models.CharField(max_length=300) description = models.TextField() slug = models.SlugField(max_length=300, unique=True) /serializers.py class BlogListSerializer(serializers.ModelSerializer): class Meta: model = BlogPost exclude = ('id',) /views.py class BlogViewSet(ModelViewSet): queryset = BlogPost.objects.all() serializer_class = BlogListSerializer /urls.py router = DefaultRouter() router.register(r'blog', BlogViewSet, basename='blog') urlpatterns = router.urls Now, I can access the url as below: list https://localhost:8000/blog retrieve https://localhost:8000/blog/1 As You can see that the retrieve url can be called using the pk or id. But I have created a model field called slug and its unique. My question is that how do I modify the retrieve url so that I can call the retrieve url using the slug field. For example: https://localhost:8000/blog/test-slug Note: Why do I want to create a url using slug? Answer: I want to use the urls for sitemap. -
Django static in if statement
I am trying to display either or (<img> or <h1>) if an image is retrieved from a static URL. So if this fails to load an image. {%for team in object_list|slice:":1"%} <img src="{% static "/img/Teams/" %}{{team.teamname}}.png" class="mx-auto mb-1" alt="{{team.teamname}}"> {%endfor%} I would like to display a <h1> and have none of the code above loaded. {%for team in object_list|slice:":1"%} <h1>{{team.teamname}}</h1> {%endfor%} Im really unsure about the best way to go about resolving this condition. Is it possible to use a {% if ...%} or some type of javascript? Thank you for any input. -
Positional Argument missing "status"
In Django: re_path(r'^accept_friend_request(?P<uidb64>[0-9A-Za-z_\-]+)/$', accept_friend_request, name = 'accept_friend_request') How do I add status as parameter in url pattern of string in template as well as in re_path? <a class="btn btn-primary" href="{% url 'accept_friend_request' uidb64=uid %}">Yes</a> def accept_friend_request(request, uidb64, status): uid= urlsafe_base64_decode(uidb64).decode() friend_user = User.objects.get(pk=Friend.to_user.id) f = Friend.objects.filter(friend_id = friend_user) if f: f.status=status f.save() return request, "users/friend_list.html", {"uid":uidb64, "status":status} -
Update partial serializer data
I am manually creating a model instance with Job.objects.create() but I want to use self.serializer.create() but I don't know how to add remaining partial data. Now I just want class JobCreationView(generics.CreateAPIView): queryset = Job.objects.all() serializer_class = JobCreatorSerializer def create(self, request, *args, **kwargs): rounds = RoundSerializer(data=request.data['rounds'], many=True) rounds.is_valid(raise_exception=True) eligibility = EligibilitySerializer(data=request.data['eligibility']) eligibility.is_valid(raise_exception=True) job = self.serializer_class(data=request.data['basic'], partial=True) job.is_valid(raise_exception=True) # after running all `is_valid` we confirm that there is no error data = dict(request.data) del data['rounds'] del data['eligibility'] job = Job.objects.create( **data['basic], # company can't be null company=request.user.account.company, # eligibility can't be null eligibility=eligibility.save() ) job.rounds.set(rounds.save()) return Response({ 'detail': f'Created Job {job.id}' }, status=201) I want something like this rounds = RoundSerializer(data=request.data['rounds'], many=True) rounds.is_valid(raise_exception=True) eligibility = EligibilitySerializer(data=request.data['eligibility']) eligibility.is_valid(raise_exception=True) job = self.serializer_class(data=request.data['basic'], partial=True) job.is_valid(raise_exception=True) job.validated_data['eligibility'] = eligibility.save() job.save() job.rounds.set(rounds.save()) The actual question that how to update serializer data after checking is_valid. -
How to pass kwargs from ModelAdmin to ModelForm
I have a ModelForm named MemoForm which gets passed the user from a view but I am not sure how to pass the user from the ModelAdmin to the MemoForm. MemoForm: class MemoForm(forms.ModelForm): title = forms.CharField() content = forms.CharField(widget=forms.Textarea) important = forms.CheckboxInput() receiver = forms.ModelMultipleChoiceField( queryset=None, required=True, widget=forms.CheckboxSelectMultiple ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') # passing in the user super(MemoForm, self).__init__(*args, **kwargs) self.fields['receiver'].queryset = EmployeeType.objects.filter( casino=self.user.casino ) ModelAdmin: class CustomMemoAdmin(admin.ModelAdmin): form = MemoForm def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) if not request.user.is_superuser: self.fields = ( 'title', 'content', 'important', 'receiver', 'read', 'unread', 'word_file', ) self.filter_horizontal = ('casino',) return form(user=request.user) # passing the user through the form here. I have a couple questions: Both the view and the admin can use the same form, correct? If so, how do I pass the user to the MemoForm from the ModelAdmin? This is the error I get when I try to add a memo from the Admin panel with these settings: TypeError at /admin/memos/memo/add/ 'MemoForm' object is not callable -
Django: What is the escape() function used for?
I am trying to make a calendar in Django, and in one of the tutorials I am reading there is the following line of code: from django.utils.html import conditional_escape as esc In the Django documentation it says that conditional_escape() is ' Similar to escape(), except that it doesn't operate on pre-escaped strings'. The documentation for escape() says: 'Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML'. I have found an example usage of escape(): from django.utils.html import escape escape("<strong style='font-size: 12px'>escaped html</strong>") Output: '&lt;strong style=&#39;font-size: 12px&#39;&gt;escaped html&lt;/strong&gt;' What is the purpose of the escape() function? I have searched online but all the sites just talk about what it does. I am not sure why one would want to use this function. Any insights are appreciated. -
How to pass a value coming from "POST" into excel or csv using Django
I'm trying to get a value coming from a POST method into excel or csv using xlwings, at this point I do not care much which excel library to use, here some example: <form action="{% url 'contact' %}" method="post"> {% csrf_token %} <input type="text" name="test123"> <input type="submit" value="uPLOAD"> </form> def upload(request): if request.method=='POST': file1 = request.FILES["document"] df = tabula.read_pdf(file1, lattice=True, pages='all', multiple_tables=True) #would like to pass "df" value to an excel or csv file but also display it as below return render(request, 'main.html', {"TEST2": file1.name, "content": df[1]}) else: return redirect(request, 'home.html') Either passing the value of "df" to excel-csv file, or set a button in the display page to download the value into excel-csv, any help?? -
Error happened just for the first time when connecting to a db via django
I have been trying to connect to a db via django. Here is a part of my code inside a view function: >>> from django.db import connections >>> conn = connections['example_conn'] Everything is fine until (I've truncated a little bit): >>> conn.cursor() Traceback (most recent call last): File "<console>", line 1, in <module> in cursor return self._cursor() in _cursor self.ensure_connection() in ensure_connection self.connect() in connect self.init_connection_state() in init_connection_state if self.features.is_sql_auto_is_null_enabled: in __get__ res = instance.__dict__[self.name] = self.func(instance) in is_sql_auto_is_null_enabled cursor.execute('SELECT @@SQL_AUTO_IS_NULL') in execute return super().execute(sql, params) in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) in _execute_with_wrappers return executor(sql, params, many, context) in _execute return self.cursor.execute(sql) in execute return self.cursor.execute(query, args) in execute res = self._query(query) in _query self._post_get_result() in _post_get_result self._rows = self._fetch_row(0) in _fetch_row return self._result.fetch_row(size, self._fetch_type) ValueError: invalid literal for int() with base 10: '' But something more weirder has happened: >>> conn.cursor() <django.db.backends.utils.CursorDebugWrapper object at 0x1064fb668> I have no idea why running the same command the second time would operate normally(and all other tries after the first one is fine), can anyone help me please? Note Django version: 2.2.4 Python3 version: 3.6.5 -
Django Prevent Customers From Buying A Different Paid Membership If They Currently Have One
I am having trouble figuring out the logic of my code to be able to prevent customers from buying another membership if they currently have one already (see image links below). For example, if they are paying for a Professional Membership, I do not want them to be able to click the Select button for Enterprise. If they are an Enterprise paying customer, I do not want them to be able to pay for a Professional Membership. I also do not want customers to be able to type into the address bar /memberships/payment/ payment page to be able to pay for a different membership. membership_list.html or /memberships/ url code: {% for object in object_list %} <div class="col-sm-4 col-md-4"> <h2>{{ object.membership_type }}</h2> <p>Price: ${{ object.price }}<small>/month</small></p> <h4>Included Courses</h4> <ul> {% for course in object.course_set.all %} <li>{{ course.title }}</li> {% endfor %} </ul> {% if object.membership_type != 'Free' %} <form method="POST" action="{% url 'memberships:select' %}"> {% csrf_token %} {% if object.membership_type != current_membership %} <button class="btn btn-primary">Select</button> {% else %} <small>This is your current membership</small> {% endif %} <input type="hidden" name="membership_type" value="{{ object.membership_type }}"> </form> {% endif %} </div> {% endfor %} Images: https://imgur.com/a/Io2hhOW https://imgur.com/a/K2mfY4v Views.py and models.py code: https://dpaste.de/3j53 I would … -
Django: apply validator at model level instead of column level
Let's say I have the following Django model: class PersonClub(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) club = models.ForeignKey(Club, on_delete=models.CASCADE) year = models.PositiveSmallIntegerField() class Meta: unique_together = ("person", "club", "year") I need to apply a validator at the model level that enforces this rule: A person can belong to only 3 different clubs in a given year. What's the best way to do this? I imagine my validator should look something like this, but I have no idea where to put it: from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_annual_clubs_per_person(obj): count = PersonClub.objects.filter(person=obj.person, year=obj.year).count() if count >= 3: raise ValidationError( _("%(person)s has exceeded max clubs for %(year)s"), params={"person": obj.person, "year": obj.year}, ) -
Django Forms throwing ValueError
I have two functions: create_questions and edit_questions; however, the former throws an error stating invalid literal for int() with base 10: 'create_question' while the latter just works fine. I cannot understand why this is happening because they are basically the same function. views.py def create_question(request): form = QuestionForm() if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid: question = form.save(commit=False) question.author = request.user question.save() messages.success(request, "Question created successfully") return HttpResponseRedirect(reverse_lazy('questions:question_detail', kwargs={'pk': question.pk})) return render(request, 'questions/question_form.html', {'form': form}) def edit_question(request, pk): question = get_object_or_404(models.Question, pk=pk) form_class = QuestionForm form = form_class(instance=question) if request.method == "POST": form = form_class(request.POST, instance=question) if form.is_valid: form.save() messages.success(request, "Question updated successfully") return HttpResponseRedirect(reverse_lazy('questions:question_detail', kwargs={'pk': question.pk})) return render(request, 'questions/question_form.html', { 'form': form, 'question': question }) forms.py class QuestionForm(forms.ModelForm): class Meta: model = models.Question fields = [ 'title', 'body', 'tags' ] models.py class Question(models.Model): author = models.ForeignKey(Postechian, on_delete=models.CASCADE) title = models.CharField(max_length=255, default="", null=True) tags = models.ManyToManyField(Tags(), blank=True) body = models.TextField(default='') rank = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ["-created_at", "-updated_at"] def __str__(self): return self.title urls.py path('create_question/', views.create_question, name="create_question"), path('edit_question/<pk>', views.edit_question, name="edit_question"), I would appreciate any help. -
Resend account activation email
so I created a template where users can register on my site. After filling the registration form an activation email is sent to the users email address. In case the user didn't receive an email I want to make it possible to resend the activation email. How do I do this? Here is my code: views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import AuthenticationForm from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from django.contrib.auth.models import User from django.core.mail import EmailMessage from django.conf import settings from .forms import UserSignUpForm from .token_generator import account_activation_token def signup_view(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('accounts/email_templates/account_activation.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(email_subject, message, to=[to_email]) email.send() # TODO: resend activation email return HttpResponse('We have sent you an email, please confirm your email address to complete registration') else: form = UserSignUpForm() return render(request, 'accounts/signup.html', {'form': form, 'project_name': settings.PROJECT_NAME}) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models … -
error when pip install mysqlclient in mac
when I try to pip install mysqlclient for python show this error ERROR: Command errored out with exit status 1: command: /Users/als/Desktop/Projects/sin/venv/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/pip-egg-info cwd: /private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/ Complete output (12 lines): /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup.py", line 16, in <module> metadata, options = get_config() File "/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup_posix.py", line 61, in get_config libs = mysql_config("libs") File "/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup_posix.py", line 29, in mysql_config raise EnvironmentError("%s not found" % (_mysql_config_path,)) OSError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django queryset with aggregation and filtered LEFT JOIN multiple levels deep
Simplified models are below. Basically think of this as: you have a bunch of Recipes and you have Users who can upload all the ingredients they have in their pantry. You can then tell them which Recipes they have ingredients for (and if they have ALL ingredients for a Recipe). Models class Recipe(models.Model): name = models.CharField(max_length=255) ingredients = models.ManyToManyField( 'Ingredient', blank=True, through='RecipeIngredient') class Ingredient(models.Model): name = models.CharField(max_length=255) type = models.CharField(max_length=255, blank=True) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe) ingredient = models.ForeignKey(Ingredient) amount = models.FloatField(_('amount'), null=True, blank=True) unit = models.ForeignKey(Unit, blank=True, null=True) class UserIngredient(models.Model): LIST_TYPE_CHOICES = [ ('PANTRY', 'My Pantry'), ('SHOPPING_LIST', 'My Shopping List'), ] user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name=RELATED_NAME) ingredient = models.ForeignKey( Ingredient, on_delete=models.CASCADE, related_name=RELATED_NAME) list_type = models.CharField(max_length=255, choices=LIST_TYPE_CHOICES) SQL / Queryset SELECT r.id, r.name, COUNT(1) AS num_ingredients, COUNT(ui.ingredient_id) AS num_matched FROM core_recipe AS r INNER JOIN core_recipeingredient AS ri ON r.id = ri.recipe_id LEFT JOIN users_useringredient AS ui ON ( ri.ingredient_id = ui.ingredient_id ) AND ui.user_id = '<user_id>' AND ui.list_type = 'PANTRY' GROUP BY r.id, r.name HAVING COUNT(1) = COUNT(ui.ingredient_id) # Or, if we want Recipes the user has ANY ingredients for: # COUNT(ui.ingredient_id) > 0 What I have right now for the queryset to try to reproduce this: user_filter … -
Serialize ManyToManyFields with different serializers in ViewSets
I have a model with ManyToMany relations which I call containers. In my API I want to get the entry that match a certain ID in this container. For example, I want to have the container with the ID "2" in the beer_container. But of course only the container which is available in the TotalOrder. My model looks like this: class TotalOrder(models.Model): beer_container = models.ManyToManyField(BeerContainer, blank=True) foreign_beer_container = models.ManyToManyField(ForeignBeerContainer, blank=True) ..... My serializer: class TotalOrderSerializer(serializers.ModelSerializer): beer_container = BeerContainerSerializer(many=True) soft_drink_container = SoftDrinkContainerSerializer(many=True) .... class Meta: model = TotalOrder fields = '__all__' In the views.py I have my TotalOrderListCreate class, which returns the whole total order with its containers. And this works very well. class TotalOrderList(generics.ListAPIView): serializer_class = TotalOrderSerializer def get_queryset(self): table_number = 'table_number' try: table = Table.objects.filter(number=self.kwargs.get(table_number)) queryset = TotalOrder.objects.filter(table__in=table) except (Table.DoesNotExist, TotalOrder.DoesNotExist): return [] return queryset But now, I want to get one container with its ID from that TotalOrder. For example: api/total-order/1/beer_container/2. I have tried this way, but I don't know how to return my queryset into the TotalOrderSerializer because now I have for example the data of an BeerContainerSerializer. I've tried this, but without any luck. class TotalOrderDetail(generics.ListAPIView): serializer_class = TotalOrderSerializer def get_queryset(self): table_number = self.kwargs.get('table_number') order_id = … -
How to render a template from a new app on django-cookiecutter
I am having trouble with rendering a template from an app using Django-cookiecutter! I am using Django-cookiecutter for my project and I am trying to create a new blog app in my project and I have kinda done everything following this tutorial: Creating a blog part but I am stuck at the part where I am trying to render the template from my new app called algo_explained. I tried following the user app inside the sample project but no luck. Here's the link to my project on github Here's what I have so far: App views explain_algorithms/explain_algorithms/algo_explained/views.py from django.shortcuts import render from explain_algorithms.algo_explained.models import Post, Comment from explain_algorithms.algo_explained.forms import CommentForm #blog_index will display a list of all your posts. def blog_index(request): posts = Post.objects.all().order_by("-created_on") context = { "posts" : posts, } return render(request, "blog_index.html", context) app-specific URL explain_algorithms/explain_algorithms/algo_explained/urls.py from django.urls import path from . import views app_name = "algo_explained" urlpatterns = [ path("blog", views.blog_index, name="blog_index"), ] main project URL explain_algorithms/config/urls.py I do have admin and all other routes I just wanted to share what's important! urlpatterns = [ path("users/", include("explain_algorithms.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here path("algo_explained/", include("explain_algorithms.algo_explained.urls", namespace = "algo_explained")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
testing django forms with pytest failing
I am not sure why the assertion below is failing. Can someone please give me a feedback, I am new to pytest with django. test.forms @pytest.fixture def product(): month = Month.objects.create(name="november", slug="november") month.save() user = User.objects.create(username="james", password="password") user.save() obj = Product.objects.create( user=user, name="broom", price=19.99, quantity=1, month=month, ) obj.save() data = { 'user':user, 'name':obj.name, 'price':obj.price, 'quantity':obj.quantity, 'month':month } form = ProductForm(data=data) yield form def test_product_form_with_data(product): assert True is not None assert True == product.is_valid() Below is what is am getting from the terminal. Traceback error. _______________________________________________________________________________________ test_product_form_with_data ________________________________________________________________________________________ product = <ProductForm bound=True, valid=False, fields=(name;price;quantity;month)> def test_product_form_with_data(product): assert True is not None > assert True == product.is_valid() E assert True == False E -True E +False tests/test_forms.py:42: AssertionError I would really appreciate a feedback to help me understand what I am doing wrong trying to test this form with data while using fixture. Looking at the data returned, I suspect that the user may be the problem because it is not returned but i tried different alternative and still same outcome. -
Detect URLs and #tags in Django CharField and add style to it
For now on I have in my template a paragraph like this <p class="...">{{ post.content }}</p> and if this Post's content contains a link or #hashtag it is rendered as a normal text with the rest of the post. How can I customize it? For example change text-color and add tag around it? -
Django - Annotate with count across ManytoMany relationships (refrase)
Django - Annotate with count across ManytoMany relationships I am not able to find the way to annotate a queryset with a count of how many times an element is used in a many-to-many relationship. class Profile(models.Model): [...] # Profile can have multiple roles roles = models.ManyToManyField('Role', blank=True) [...] class Role(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(blank=True, max_length=30) description = models.CharField(blank=True, max_length=300) [...] For example I would have 5 roles: Role1 Role2 Role3 Role4 Role5 And 2 profiles with following roles assigned: Profile1 Role 1 Role 2 Profile2 Role 1 Role 3 Role 4 I need to have the oposite than @ha-duy: Profile: name, role_count=2 Profile: name, role_count=3 Any ideas? Thanks! -
Django request.body always printing nonsense result (b'')
I am new to django , I started working on an existing Vuejs/Django project to easily understand how things are working . I wrote a new specific view in views.js def hello(request): print(req.body) return HttpResponse('hello') Then in urls.py I added the following: path('hello/',views.hello,name='hello') At first I tried sending a plain/text , but the print function shows the following b'' I tried printing request.data but it says WSGIRequest' object has no attribute 'data' I tried sending a JSON and using the following : body_string = request.body.decode("utf-8", "ignore") data = json.loads(body_string) Result : Expecting value: line 1 column 1 (char 0)Expecting value: or: data = json.loads(request.data.get('_content')) Result: 'WSGIRequest' object has no attribute 'data' none of that seems to be working . The app I am working on seems to be working fine but it has no specific URL that's way I am stuck as I have no example , even here I couldn't find anything that helps. -
Django DRF: How to make a todo item dependent to another item
Hi I am building an todo app according to a tutorial and I want to improve it a bit. I want a todo item dependent to another. For example if todo1 has dependency to todo2, it shouldn't allow me to check todo1 before complete todo2. Here is my models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User class TodoList(models.Model): name = models.CharField(max_length=200, default="blank title") is_completed = models.BooleanField(default=False) completed_at = models.DateTimeField(default=datetime.now(), null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: verbose_name = "Todo List" verbose_name_plural = "Todo Lists" ordering = ["name","created_at", "is_completed", ] def __str__(self): return self.name class TodoItem(models.Model): name = models.CharField(max_length=200, default="blank title") todo_list = models.ForeignKey(TodoList, on_delete=models.CASCADE, null=False) description = models.TextField(max_length=200, default="Blank text") is_completed = models.BooleanField(default=False) completed_at = models.DateTimeField(default=datetime.now(), null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField(default=datetime.now(), null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) previous_item = models.IntegerField(default=0) class Meta: verbose_name = "Todo Item" verbose_name_plural = "Todo Item" ordering = ["id","created_at", "is_completed","deadline","name" ] def __str__(self): return self.name Views.py from django.shortcuts import render from rest_framework.views import APIView from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from rest_framework import viewsets, permissions, status from rest_framework.decorators import action, api_view from rest_framework.response import Response from …