Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultilingualQuerySet always returns empty list
I have a website with support for 2 languages but I have a problem with switching url's. So when user clicks link that leads to some category I get list index out of range my model class Category(models.Model): category = models.CharField(max_length=20,unique=True) def __str__(self): return self.category translations.py for my model class CategoryTranslationOptions(TranslationOptions): fields = ('category',) translator.register(Category, CategoryTranslationOptions) my code view that is responsible for getting product with said category categoryList = Category.objects.all() categoryName = categoryList.filter(Q(category_pl=categorySlug) | Q(category_en=categorySlug)) productsInfo = Product.objects.filter(category=categoryName[0]) What I'm doing in categoryName is looking for name in two languages in case if user switches language mid browsing. Then I get the first value of it because it's a list but the list is empty. update when I printed out categoryList = Category.objects.all().values() I didn't saw any translation-related fields but i can see them in admin panel so it is the case of not getting correct query from database -
Wher to look for custom teplate tag in django
I'm trying to understand how netbox application is working (https://github.com/netbox-community/netbox). In a template "sidenav.html" it uses a custom tag "nav" this way: {% load nav %} {% nav %} Can you tell me what's behind that and where or how can I find it? -
List view and a dynamic List view in Django
I am brand new to Python & Django programming. I would like to display a List view category and a dynamic List view on the same Web page which will display a list of subcategories that belong to the selected category. -
How can I make a decorator in models.py?
I have a football Team class in my django Model. I made 3 methods of win, draw and lose where the self.Points_of_the_season will be modified accordingly ( +3 for win, +1 for draw and +0 for lose). But When I wrote those methods, I have to change the self.Match_Played with each call of the 3 methods. How can I make a decorator called @play_match which will add 1 to the concerned field? This is the code of models.py: class Team(models.Model): Team_name = models.CharField(max_length=255) Foundation_year = models.IntegerField() Points_of_season = models.IntegerField(default=0) Match_Played = models.IntegerField(default=0) League = models.ForeignKey(League, on_delete=models.CASCADE) def __str__(self): return f"{self.Team_name}-{self.Foundation_year}" @play_match def win(self): self.Points_of_season += 3 @play_match def draw(self): self.Points_of_season += 1 @play_match def lose(self): pass -
TF400898: An Internal Error Occurred. Activity Id: 1fc05eca-fed8-4065-ae1a-fc8f2741c0ea
i’m trying to push files into git repo via azure API but getting activity_id error. I followed their documentation and trying to add simple file in my repo. Here is my code: import requests, base64 pat_token = "xxxx-xxxxx-xxxx" b64Val = base64.b64encode(pat_token.encode()).decode() payload = { "refUpdates": [ { "name": "refs/heads/main", "oldObjectId": "505aae1f15ae153b7fc53e8bdb79ac997caa99e6" } ], "commits": [ { "comment": "Added task markdown file.", "changes": [ { "changeType": "add", "item": { "path": "TimeStamps.txt" }, "newContent": { "content": "# Tasks\n\n* Item 1\n* Item 2", "contentType": "rawtext" } } ] } ] } headers = { 'Authorization': 'Basic %s' % b64Val, 'Content-Type': 'application/json', } params = ( ('api-version', '6.0'), ) response = requests.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repo}/pushes', headers=headers, data=payload, params=params) Anyone knows how to solve this issue? I have also added this issue on their developer community -
Why is current admin not shown in django app?
I created a mock user profile in Django admin in the admin/auth/user view and assigned the user with all permissions (active, staff status, superuser status). In admin/<app_name>/user I gave the user all authorization permissions. In the Django admin panel, when I hit view site and enter the home view of the django application, the current user is different from the one that was visiting the admin page. Why is the current user different from the admin user? -
Defining view function for displaying postgres data in django
I created the wines database in postgresql (containing ID, names etc), and inserted around 300 observations. I would like to display names of every wine in drop menu with django. The urls.py are properly setted up. App name inside the project is: jacques. What have I done so far: models.py from django.db import connection from django.db import models class ListWines(models.Model): name = models.CharField(max_length=200) views.py from django.shortcuts import render from jacques.models import ListWines def showallwines(request): wines = ListWines.objects return render(request, 'main.html', { 'name':wines } ) main.html <!DOCTYPE html> <head> <body> <select> <option disabled = "True" selected>Select your favourite wine!</option> {% for wines in showallwines %} <option>{{wines.name}}</option> {% endfor %} </select> </body> </head> The postgres database is named jacques (column containing data that I want to display is name) is connected with app by setings.py, however it doesn't show names. How should I redefine my functions in order to see display in main.html drop menu? -
Celery beat not sending task to worker in heroku, configured in a single dyno in free tier
I am making a website, where the user has to accept an agreement and then an expiration date is set for the user. On that date the contract is supposed to get expired by setting a contract_expired boolean field to True and sending an email to the respective user about the same. I used celery beat for this. Now since the site is in tessting phase, it is hosted in a free tier dyno in heroku, so I had to configure one dyno for web and the other for both celery worker and beat. I scheduled a task for beat where it would run daily on 9 am, to check the exipiries for the users and then do the work as mentioned above. This function was running correctly when I was testing it in the localhost, i.e., by running two seperate terminals for worker and beat. But today at 9 am it did not run in heroku. Below are the codes that i wrote for the entire process procfile release: python manage.py migrate web: gunicorn jgs.wsgi --log-file - celeryworker: celery -A jgs.celery worker & celery -A jgs beat -l INFO & wait -n celery.py from __future__ import absolute_import, unicode_literals import … -
How to use temporary file from form upload - Python Django
I have a form where users can upload up to 1,000 images at a time. I have changed my FILE_UPLOAD_MAX_MEMORY_SIZE in Django settings to 0 so all files uploaded via a form are written to a temp directory in my root folder. I am then trying to process the images with OpenCV. original_img = cv2.imread(temp_image.temporary_file_path()) gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY) temp_image.temporary_file_path() This returns the absolute file path of the temp image in a string format So I put that in the cv2.imread, however, it creates a NoneType instead of a numpy array like it should and then my program cannot run when it reaches gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY) How do I read the temporary file into OpenCV? Any help is much appreciated. -
Issue finding which comment to reply to using django-mptt for nested comments in a blog
I'm trying to create a nested comment system with djano-mptt. I have got it working and the comments are displaying as designed. However, when the issue I'm having is coming up with the logic for the user to choose which comment to reply to. Through the form I can display all the post and parent field and that allows the user to select a post and comment. Although the issue being they can comment on any post and any comment in the list. Trying to implement logic where if the user is on that post they can only comment on that post and can choose which comment (if they want) to reply to. Here is the model: class Comment(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class MPTTMeta: order_insertion_by = ['created_on'] def __str__(self): return f"Comment {self.body} by {self.name}" The view: def CommentView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.name = request.user.username comment = comment_form.save(commit=False) comment.post = post comment.save() else: comment_form = CommentForm() return HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) The form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('post', 'body', 'parent',) labels = { … -
no such table: users_customuser in Django
I am trying to create an extended Custom User model that adds a level field of 0 to the User model which is not displayed on the form. But when I try to do this, I get the error no such table: users_customuser. I am new to Django. How can I implement what I described earlier and what I am doing wrong? Just in case I have done migrations... Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users … -
jQuery .addClass applying to everything
I have a like button that uses jQuery. The like button works as expected however due to the way I have it setup it changes every icon on the page to a heart code: if (data.liked) { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $("i").addClass("fa fa-heart-o liked-heart"); //problem line } else { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $("i").addClass("fa fa-heart-o unliked-heart"); //problem line From what i userstand the issue is that I am appending the class fa fa-heart-o ... to all i elements. How can I just apply it to the like button full code: <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $( "i" ).addClass( "fa fa-heart-o liked-heart" ); } else { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $( "i" ).addClass( "fa fa-heart-o unliked-heart" ); } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> <a class="like-btn" data-href='{{ post.get_api_like_url }}' data-likes="{{ post.likes.count }}" href="{{ post.get_like_url }}"><i class="{% if userliked %}fa fa-heart-o … -
AttributeError: 'FlaubertForSequenceClassification' object has no attribute 'predict'
I am trying to classify new dataset from best model after loading but I get this error: best_model_from_training_testing = './checkpoint-900' best_model= FlaubertForSequenceClassification.from_pretrained(best_model_from_training_testing, num_labels=3) raw_pred, _, _ = best_model.predict(test_tokenized_dataset) predictedLabelOnCompanyData = np.argmax(raw_pred, axis=1) Traceback (most recent call last): File "/16uw/test/MODULE_FMC/scriptTraitements/classifying.py", line 408, in <module> pred = predict(emb, test_model) File "/16uw/test/MODULE_FMC/scriptTraitements/classifying.py", line 279, in predict raw_pred, _, _ = model.predict(emb_feature) File "/l16uw/.conda/envs/bert/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1130, in __getattr__ raise AttributeError("'{}' object has no attribute '{}'".format( AttributeError: 'FlaubertForSequenceClassification' object has no attribute 'predict' -
Run Djano Project On Github
I am new on Full Stack developer. I make a Django project it is run on localhost:8888. I want to run it on github. But I don't know how i do it. Please, Help me. How i run Django project on Github. -
How to get username from user id in template
This is probably a simple answer but I cant figure it out. I have a comment system on my blog. I need to get the username from the user id. I get the id from which is a fk to the users table {{child_comment.parent_userdata_id}} Usually when I need to do this I just user .username but it doesn't seem to work in this case -
How to save MultyPlygon in Django model field
I'm trying to save MultyPlygon to Dajngo MultiPolygonField but get this error: TypeError: Cannot set Plot SpatialProxy (MULTIPOLYGON) with value of type: <class 'shapely.geometry.multipolygon.MultiPolygon'> My actual code is model.py: ... poligon = gis_models.MultiPolygonField(verbose_name=_('Polygon'), blank=True, null=True) ... gml_parser.py: self.plot.poligon = geometry_plot self.plot.save() The geometry_plot object type is <class 'shapely.geometry.multipolygon.MultiPolygon'> Any idea ? Thanks in advance. -
Logging in Django does not work when using uWSGI
I have a problem logging into a file using python built-in module. Here is an example of how logs are generated: logging.info('a log message') Logging works fine when running the app directly through Python. However when running the app through uWSGI, logging does not work. Here is my uWSGI configuration: [uwsgi] module = myapp.app:application master = true processes = 5 uid = nginx socket = /run/uwsgi/myapp.sock chown-socket = nginx:nginx chmod-socket = 660 vacuum = true die-on-term = true logto = /var/log/myapp/myapp.log logfile-chown = nginx:nginx logfile-chmod = 640 Thanks in advance -
Is there any other option for on_delete other than models.CASCADE for a ForeignKey in Django models>
Why is the on_delete property of a ForeignKey in a Django model not default? That should be the case if there is no other option other than models.CASCADE. Is there any other option for the on_delete property? -
URL with multiple parameters throws a NoReverseMatch error
I aim to redirect the view after the form has been saved. However django keeps throwing a NoReverseMatch error. Is there a step that I've missed or a misconfiguration? views.py def add_carpet(request): context_dict = {} carpet_form = forms.CarpetForm() if request.method == "POST": carpet_form = forms.CarpetForm(request.POST) if carpet_form.is_valid(): carpet = carpet_form.save() return redirect(reverse( "dashboard_add_images", kwargs={ "model_type": "carpet", "id": carpet.id } )) context_dict["carpet_form"] = carpet_form return render( request, 'dashboard/add_carpet.html', context_dict ) def add_images(request, model_type, id): ... urls.py urlpatterns = [ path('add_carpet', views.add_carpet, name="dashboard_add_carpet"), path('add_images/<str:model_type>/<uuid:id>', views.add_images, name="dashboard_add_images"),] An example redirect url after a form has been submitted is this: http://127.0.0.1:8000/dashboard/add_images/carpet/97afd259-6ec4-48fc-869f-2a00bbe29c70 Error: Reverse for 'dashboard_add_images' with no arguments not found. 1 pattern(s) tried: ['dashboard/add_images/(?P<model_type>[^/]+)/(?P<id>[^/]+)$'] -
Go to another page without refresh [Django]
How to achieve going to another page without refreshing after for example clicking a link to another URL. More examples, I have a list of books display and when I clicked on one of the book, it will redirect me to the selected book page. This is the example of the code link. <a class="link" href="{% url 'books:view_book_detail' obj.book.name obj.pk %}">View book</a> I know about the history.pushState() but how to actually use it ? Can it be use with URL from Django. Are there any method else then stated ? -
ValueError: Field 'id' expected a number but got 'create'
When I try to request this class: class CourseCreate(CreateView): model = Courses form_class = CoursesForm template_name = 'main_app/courses/course_form.html' success_url = reverse_lazy('courses') def form_valid(self,form): messages.success(self.request, f"Course created successfully") return super().form_valid(form) I got this error: ValueError at /academiaweb/courses/create Field 'id' expected a number but got 'create'. models.py: class Courses(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.TextField() year = models.ForeignKey(SchoolYears,on_delete=models.CASCADE) class Meta(): verbose_name = 'Course' verbose_name_plural = 'Courses' def __str__(self): return self.name Urls.py: path('courses/create',views.CourseCreate.as_view(),name='course_create'), -
How do I prepopulate Foreign key fields on django admin inline?
I have Service Groups and Services. Together, they create a unique relation GroupService which includes some other foreign keys.So, in django admin, upon creation of a group, I want to prepopulate service inlines with two default services' ids. I've tried overriding the BaseInlineFormSet for my inline but no success. Here's what I've tried, now it gives me KeyError: "Key 'id' not found in 'GroupServiceForm'. Choices are: counter, deduction, numerator, service.". When I tried to implement it using self.empty_form, I actually succeeded at displaying default services' foreing keys but could not save the form even if I had all my fields filled in. class CustomInlineFormSet(BaseInlineFormSet): def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None, **kwargs): super().__init__(data=data, files=files, instance=instance, save_as_new=save_as_new, prefix=prefix, queryset=queryset, **kwargs) default_services = Service.objects.filter( is_default=True).values_list('id', flat=True) services = [form['service'].initial for form in self.forms] for default_service in default_services: if default_service not in services: empty_form = self.form(initial={'id': 12, 'group': instance.id, 'service': default_service}) # empty_form.is_valid() self.forms.append(empty_form) class GroupServiceInline(CompactInline): model = GroupService fieldsets = ( (None, {'fields': ('service',)}), ('KPI', {'fields': ('counter', 'deduction', 'numerator')}), ) formset = CustomInlineFormSet extra = 2 -
Selenium: get file URL from WebElement (django, pytest)
I'm trying to test a django web app via Selenium and pytest. My test page has the following link displayed within a table (along with other links of the same format): <a href="/download_file/?file_path=serve/myid/results_XYZ.csv"><input type="button" value="Results (.csv)" /></a> I can get that webelement by using the following code: input_fields = self.driver.find_elements(By.CSS_SELECTOR, '\\input') for elem in input_fields: value = elem.get_attribute("value") if value == "Results (.csv)": csv_link = elem # more elif clauses to get the various links calling .click() on that webelement leads to a successful download of the file, so that works. Now, I also need to extract the actual download link from that element, to get the filename. What I have tried: print(mylink.get_attribute("href")) # prints None print(mylink.get_attribute('outerHTML')) # prints <input type="button" value="Results (.csv)"> print(mylink.get_attribute('innerHTML')) # prints nothing print(mylink.get_attribute("ownerElement")) # prints None The latter is surprising to me, because the following: mydic = mylink.get_property('attributes')[0] for key in mydic: print(f"\t{key}:\t{mydic[key]}") prints, among other things, ownerElement: <selenium.webdriver.remote.webelement.WebElement (session="c470b6e33d0b2fbec3f1a0e7e26dec55", element="81bdc092-0b8b-4069-a1ec-8a685fda18a5")> So I'm confused why I can't get that ownerElement. And also, why .get_attribute('innerHTML'), which I have seen advertized everywhere, does not give me anything. But mostly, I need to know: How do I get the file-url from such a download link? -
Google OAuth2 for Android using python-social-auth
I have a Django project, that implements Google OAuth2 with python-social-auth package. It works fine for Web applications. My config in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv('GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv('GOOGLE_OAUTH2_SECRET') AUTHENTICATION_BACKENDS = ( 'entity.oauth.backends.CustomGoogleOAuth2', 'entity.oauth.backends.CustomFacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_STRATEGY = 'entity.oauth.strategies.CustomStrategy' After completing the request I generate JWT tokens for the user: def jwt_do_complete(backend, login, user=None, redirect_name='next', *args, **kwargs): ... if user: if user_is_active(user): # Get the JWT payload for the user. refresh = TokenObtainPairSerializer.get_token(user) payload = { 'refresh': str(refresh), 'access': str(refresh.access_token) } else: raise RuntimeError('Unauthorized', 'The user account is disabled.', status.HTTP_401_UNAUTHORIZED) else: raise RuntimeError('Unauthorized', 'The user account does not exist.', status.HTTP_401_UNAUTHORIZED) return user, payload So the workflow of the authorization is the following: Frontend authenticates by Google form and receives code and other information. It sends it to the complete route of the Django server. Django verify the code with help of python-social-auth. Django sends back JWT tokens. Here is the complete view: @never_cache @csrf_exempt @psa(f'{NAMESPACE}:complete') def complete_with_jwt(request, backend, *args, **kwargs): """Authentication complete view""" try: user, token_info = jwt_do_complete( request.backend, _do_login, user=request.user, redirect_name=REDIRECT_FIELD_NAME, request=request, *args, **kwargs ) except RuntimeError as e: if len(e.args) != 3: raise return HttpResponse(json.dumps({ 'status': e.args[0], 'message': e.args[1], }), status=e.args[2]) return HttpResponse(json.dumps(token_info)) It works fine as I said … -
Django is taking the templates from virtualenv not from /templates for application
I am using Django 3.2.10 and I also use a template for frontend and for admin panel. My problem is that the website is loading the templates from virtualenv and not from the template folders in the applications. My current configuration is: INSTALLED_APPS = [ 'django.contrib.admindocs', 'apps.admin_volt.apps.AdminVoltConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.app', 'apps.crypto', 'apps.taskmgr', 'django_celery_results', 'apps.home', 'apps.authentication', 'debug_toolbar',] CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(CORE_DIR, "core/templates") # ROOT dir for crypto TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { ... STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = 'static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'core/static'), os.path.join(CORE_DIR, 'apps/admin_volt/static'), os.path.join(CORE_DIR, 'apps/static'), ) How can I change my configuration to ensure that the templates are taken from app/admin_volt/templates/admin and not from venv\Lib\site-packages\admin_volt\templates\admin Thank you