Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I filter out the friends of current user from a search_users function (Django)
I'm trying to filter out the friends of a user also the user themselves from a search users function, I've tried using the exclude() parameter but I'm not sure what I'm doing wrong, as you can see from my views.py the search_users function has a exclude on the end of object_list, but this didn't work. I also wanted to add a "add friend" button next to the users, which I think I've done correctly on 'search_users.html . I hope I've put as much info as you need to understand the issue. views.py from .models import Profile from feed.models import Post from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.conf import settings from django.http import HttpResponseRedirect from .models import Profile, FriendRequest from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm import random from django.core.mail import send_mail from django.urls import reverse User = get_user_model() def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) sent_to = [] friends = [] for user … -
Django Admin exclude model from index and app page
I want to hide some models from admin index page and app page. For example, these that I have visible in inlines as related objects. One more point, I want to keep the ability to work with change_view and add_view, but not list_view of that model. Tried to find any hints in admin/templates/admin/*.html files, but haven't found anything helpful. Is it possible without "hacks", monkey-patching and external libraries? -
Git-bash cannot detect "django-widget-tweaks" on active virtualenv
I have an issue regarding django-widget-tweaks on the active virtualenv using Windows 10. I have django project and I when I add widget_tweaks to INSTALLED_APPS on settings.py, it keeps give me an error like this when i run the project. But when I am using command prompt the project actually could be run. Any idea how to fix the below issue on git bash? Thank you for your time. $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module … -
Django reverse ORM join queries
I want all the rows of my (MovieMaster table) for which (SetMovie table) exists. These are my models class MovieMaster(models.Model): m_name = models.CharField('Movie Name',max_length=50) m_desc = models.CharField('Movie Description', max_length=50) m_image = models.ImageField('Movie Image',upload_to="pics/") def get_absolute_url(self): return reverse("admin_side:addmovie") def __str__(self): return self.m_name class SetMovie(models.Model): active = models.ForeignKey(MovieMaster, on_delete=models.CASCADE) show = models.CharField('Show Time', max_length=50) start_time = models.DateField() end_time = models.DateField() def get_absolute_url(self): return reverse("admin_side:setmovie") Basically I want to execute this sql query (SELECT * from MovieMaster INNER JOIN SetMovie ON MovieMaster.id = SetMovie.id). I am new at this. I am able to get all SetMovie row for MovieMaster by using models.SetMovie.objects.select_related('active') But I am not able to get all values of MovieMaster table for SetMovie table. -
How do I make the makemessages command detect default django translations (like form validation error messages)?
The site I'm developing is multilingual and the secondary language is not supported by default. I have added it in the settings file like so. EXTRA_LANG_INFO = { 'am': { 'bidi': False, # right-to-left 'code': 'am', 'name': 'Amharic', 'name_local': u'አማርኛ', #unicode codepoints here }, } The error_messages that I overwrite and use are correctly translated and detected by the makemessages command. error_messages = { 'password_mismatch': _('The two password fields didn’t match.'), } But the default validation exception error_messages that I did not overwrite do not appear in the .po translation file. It would be much easier to find out a way to make the command also render translations for those strings, as opposed to me overriding on every time it appears. Thanks. -
How would you model these database relationships? (User, Competence, Interest)
I'm working with a Django system and the thing is pretty simple actually, but one thing got me bothered and I thought that must be a better way to do it. Basically it's an internal tool for searching the developers the company has available to allocate them in projects based on their skills and interests. So let's say Employee John can add a Topic React to his list of competence and select his skills levels from 1 to 5 stars, meaning 1 = total beginner and 5 = expert. He can also select his level of interest from 1 to 5. So you can have a list like below The way this is designed at DB is like this: Table user with all relevant user information Table knowledge_topic with columns [id, label], where label is just the name of the language/tech Table knowledge_level with columns[id, knowledge_level, interest_level, topic_id, user_id] where topic_id makes the relationship to knowledge_topic table and user_id to user table The competence list endpoint can give a result like this for example: [ { "id": 2, "topic": { "id": 8, "label": "Docker" }, "interest_level": 4, "knowledge_level": 2, "user": 2 }, { "id": 5, "topic": { "id": 9, "label": … -
Error while using pghistory.BeforeDelete() of django-pghistory
I am using django-pghistory 1.2.0 to keep my changes using postgres triggers. For insert or update, it saves data to event table for both ORM and raw queries. But while using delete, it throws errors. My model: @pghistory.track( pghistory.AfterInsert('after_insert'), pghistory.AfterUpdate('after_update'), pghistory.BeforeDelete('before_delete') ) class TestModel(models.Model): int_field = models.IntegerField() char_field = models.CharField(max_length=16) Test API for CRUD operation: class TestModelAPI(APIView): def post(self, request, *args, **kwargs): obj = TestModel.objects.create(int_field=1, char_field='c1') obj.int_field = 2 obj.char_field = 'c2' obj.save() obj.delete() return JsonResponse( data={'message': 'success'}, status=200, ) My INSTALLED_APPS: INSTALLED_APPS = [ ............., 'pgtrigger', 'pgconnection', 'pghistory', ] My database settings: DATABASES = pgconnection.configure({ "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "<some-value>", "USER": "<some-value>", "PASSWORD": "<some-value>", "HOST": "<some-value>", "PORT": "<some-value>", }, }) My error: Traceback (most recent call last): File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/pgconnection/core.py", line 85, in execute return super().execute(sql, args) psycopg2.errors.ObjectNotInPrerequisiteState: record "new" is not assigned yet DETAIL: The tuple structure of a not-yet-assigned record is indeterminate. CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent" ("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())" PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
Add buyitnow functionality to django auction website
I'm new to django and to programming and I want to add buy it new functionality to an auction website. Like ebay, so you can both bid and buyitnow(for a specific price defined for seller) an item. Can you help me with the logic? How these two think can combined? Thank you in advance. -
How to solve UnicodeDecode error in django
I was making a project but I accidentally deleted the git changes. The files were all lost but fortunately i recovered them using Recuva. The problem i am now facing is this, when i open the website, the first page shows up normally but the when i click that object to get its details, i get this error: UnicodeDecodeError at /cartoon/2 'utf-8' codec can't decode byte 0x9d in position 0: invalid start byte can someone help me with this, thank you in advance -
Array validation using AJAX: show error message
Trying to validate arrays via FormRequest validation. I can access the error message for the field 'name' as data.responseJSON.error.name[0] and show it to the user. error: function(data, xhr, errmsg, err){ console.log("data") console.log(data.responseJSON) $(".form-alert").fadeIn(); $(".form-error").text(data.responseJSON.error.phone[0]); This works fine. With the same way i access error messages for other fields, however i cannot modify script to handle all errors, i can make it work only with one field as shown above. How can i modify script to catch errors for example for 'field1', 'field2'. Thank you -
Use django sessions for requests not from a browser (terminal + mobile app)
I'm currently working on a mobile app development and using Django for backend (and Kivy for GUI frontend) services and database and trying to use sessions for login purposes. As I'm compiling the app from the terminal, everytime I launch build and launch it, try to log in, a new session is created. I can see that in the database as I'm the only one to test it and that there are more than 100 rows in django.session table. The server is locally runned. So what I do, at the moment is: get request to check if something is stored in request.session['used_id'] if nothing then display signin/signup forms and in this case, I created a new session at the login. Actually I've no idea on how I can use sessions to stay connected for my tests in the terminal. In the future, let users stay connected on the app on their devices might be an issue too but I've already that asnwer that can be very useful. Is there a way to do that? Thank you! -
prevent user creating if another create unsuccessful django
Probably there is the answer to this question, but I couldn't find it. How to prevent User - from django.contrib.auth.models import User, creation if userProfileSerializer creating is unsuccessful. I saw a database transaction is an option but it says While the simplicity of this transaction model is appealing, it also makes it inefficient when traffic increases. Opening a transaction for every view has some overhead. The impact on performance depends on the query patterns of your application and on how well your database handles locking. @api_view(['POST']) @permission_classes([AllowAny]) def register(request): ''' Registers user to the server. Input should be in the format: {"username": "username", "password": "1234abcd"} ''' # Put the data from the request into the serializer serializer = CreateUserSerializer(data=request.data) # Validate the data if serializer.is_valid(): # If it is valid, save the data (creates a user). serializer.save() userProfileSerializer = UserProfileSerializer(data=request.data) userProfileSerializer.context['user_id'] = serializer.data['id'] userProfileSerializer.is_valid(raise_exception=True) userProfileSerializer.save() Serializer classes class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name',) extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'organization', 'user_id') def create(self, validated_data): user_id = self.context["user_id"] user_profile = UserProfile(**validated_data, user_id=user_id) user_profile.save() … -
How to apply colour in row according to condition in python Django
table.py class resultTable(BaseTable): class Meta(BaseTable.Meta): model =Modelname attrs = {'class': 'table table-striped table-bordered table-hover row-color=green' , 'width': '70%'} fields = ( "field1", "field2 ", "status", "field4", "field5" ) admin.py @admin.register(Modelname) class resultAdmin(admin.ModelAdmin): list_display=('field1', 'field2 ', 'status','field4 ','field5') how to apply the condition in table. if the status is warring and ok the row color should be yellow. -
Running two modals works runnig a third one in a different bootstrap tab does not
I am using django-bootstrap-modal-forms. I have bootstrap tabs with crispy forms I made a modal for files and it worked; But I am trying to add two modals; one for authors the other for translators. Ill show the code that is loaded in a table. {% include "_modal.html" %} <div id="linkeddocuments"> <div class="col-12 mb-3"> {% include "_authors_table.html" %} </div> </div> <div id="searchdocumentpanel" class="container"> <div class="row"> <div class="col"></div> <div class="col"> <button type="button" class='btn btn-primary btn-danger' id='create-author-async'><span class="fa fa-plus mr-2"></span>new author async</button> <br/> <br/>Search Authors:<br/> <br/> <input type="text" id="id_search_authors"> </input> </div> <div class="col"></div> </div> <br/> <div class="col-12 mb-3"> {% include "_authors_candidates_table.html" %} </div> </div> <div id="linkeddocuments"> <div class="col-12 mb-3"> {% include "_translators_table.html" %} </div> </div> <div id="searchdocumentpanel" class="container"> <div class="row"> <div class="col"></div> <div class="col"> <button type="button" class='btn btn-primary btn-danger' id='create-translator-async'><span class="fa fa-plus mr-2"></span>new translator async</button> <br/> <br/>Search Translator:<br/> <br/> <input type="text" id="id_search_translators"> </input> </div> <div class="col"></div> </div> <br/> <div class="col-12 mb-3"> {% include "_translators_candidates_table.html" %} </div> </div> <script type="text/javascript"> $(function () { var asyncSuccessMessageCreateAuthor = [ "<div ", "style='position:fixed;top:0;z-index:10000;width:100%;border-radius:0;' ", "class='alert alert-icon alert-success alert-dismissible fade show mb-0' role='alert'>", "Success: Author was created.", "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>", "<span aria-hidden='true'>&times;</span>", "</button>", "</div>", "<script>", "$('.alert').fadeTo(2000, 500).slideUp(500, function () {$('.alert').slideUp(500).remove();});", "<\/script>" ].join(""); var asyncSuccessMessageUpdateAuthor = … -
Query from template in Django
I am coming from Ruby-on-Rail background. I have a user table and an employee table. In the index page of all the employee, I am looking to retrieve their first name which is in the user model and not in the employee table. I tried the following which is very rubyesque: {% User.objects.filter(id=employee.user_id) %} But i get the error: Invalid block tag on line 163: 'User.objects.filter(id=employee.user_id)', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Although the user_id clearly exists. What is the best way for such queries in Django please ? -
Django Rest Framework: router is not working
I have used DefaultRouter() and viewset. Here is the code from rest_framework import routers from .api import TweetViewset, OwnersTweet from django.urls import path router = routers.DefaultRouter() router.register('', TweetViewset, 'tweets') router.register('own/', OwnersTweet, 'owner') And project-level urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), path('tweet/', include('tweets.urls')) ] When I send a request to '<URL>/tweet/own/' It returned an error Not Found. But <URL>/tweet/ is working. OwnersTweet view also working fine. But I think there is smth wrong with URL. Can you help, please? -
create link of selenium file not to call link in selenium file
all fresh to codding world. I am working on python and created a random project of selenium I am tired of searching on google. I just want to create a simple link (localhost) of my selenium project. So that whenever I hit the link in a browser, it should start my project testing(opening crome->link->logging, etc). I don't want to run it from the terminal. as I want to add jquery -
CRUD web application with Bigquery?
I have a bigquery table about 1000 rows, i need to insert,delete and update values in this through a web interface(the table cannot be migrated to any other relational or non-relational database). The web application will be deployed in google-cloud on app-engine and the user who acts as admin and owner privileges on Bigquery will be able to create and delete records and the other users with view permissions on the dataset in bigquery will be able to view records only. I am planning to use the scripting language as python, server(django or flask or any other)-> not sure which one is better The web application should be displayed as a data-grid like appearance with buttons like and create,delete or view according to their roles. I have done anything like this in python,bigquery and django. I am seeing examples only related to django with their inbuilt model and not with big-query. Can anyone please help me and clarify whether this is possible to implement and how? -
Django <uuid:id> redefinition error. Pattern Problem
i've become an ErrorMessage because i think i have the wrong reference pattern in my url.py. In my models.py i create this models class Quiz(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100) details = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return '/quiz/quiz' class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) fk_quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.CharField(max_length=100) class Answer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) fk_quizfrage = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=100) correct = models.BooleanField(default=False) An in my urls.py i make refernces like this: path('quiz/<uuid:id>/', QuizDetailView.as_view(), name='quiz-detail'), I think i have to change the pattern from <uuid:id> The complete Error is: :in _parse raise source.error(err.msg, len(name) + 1) from None re.error: redefinition of group name 'uuid' as group 2; was group 1 at position 90 -
How to make it such that if comments have been edited before, an "edited" permanent message will be displayed beside the comment?
How to make it such that if comments have been edited before, an "edited" permanent message will be displayed beside the comment? So that everyone will be able to see that the comment has been edited before. (it'll be good if i can keep a copy of the original pre-edited message too, but if thats too difficult, i'm just hoping to display an "edited" permanent message will be displayed beside the comment. 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() class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) views.py def edit_own_comment(request, post_id): context = {} comment = get_object_or_404(Comment, id=post_id) if request.method == 'POST': form = UpdateCommentForm(request.POST or None, instance=comment) if form.is_valid(): obj.save() messages.success(request, 'Your comment has been edited', extra_tags='editedcomment') return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug })) form = UpdateCommentForm( initial = { "body": comment.body, } ) context['form'] = form return render(request, 'HomeFeed/edit_comment.html', context) class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() blog_post.save() forms.py class UpdateCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] def save(self, commit=True): comment = self.instance comment.body = self.cleaned_data['body'] if commit: comment.save() return comment detail.html {% for comment in … -
Django: Create a custom order of objects in django model
I'm trying to build a teaching website of sorts in Django. I have a model called Test: class Test(models.Model): test_name = models.CharField(max_length=100) test_directions = models.TextField(null=True) test_status_new = models.ManyToManyField('StudentProfile', related_name='test_status_new') test_status_good = models.ManyToManyField('StudentProfile', related_name='test_status_good') test_status_repeat = models.ManyToManyField('StudentProfile', related_name='test_status_repeat') test_repeat_due = models.IntegerField(default=6) test_status_due = models.ManyToManyField('StudentProfile', related_name='test_status_due') def __str__(self) -> str: return f"{self.test_name}" def __repr__(self) -> str: return f"<{self.test_name}>" I'd like to give them a custom ordering somehow. I am displaying them in a table like so: and would like to change the order of each individual tests from the two buttons in the Order column. If I click Up, the test moves one row up. If I click down, the test moves down one row. How would I implement something like this? -
How to disable a decorator on a method, if that method is called in django tests?
I have a function that is like: @dec_func def a(): do_something; In my django tests this function is ran in execution. Now i want that whenever the tests run my function a should not get decorated dec_func but if the function runs in development or production environment, method should be decorated. How to do so. -
Adding a second password field to Django User model
I would like to add a second password field override_password to my User model. It will be used for admin overrides so I want it to be separate to the users password. I have defined the additional password field below with 73 max because I want it to be hashed, but need advice on how to go about setting this password. User model: class User(AbstractUser): """Default user.""" #: First and last name do not cover name patterns around the globe name = CharField(_("Name"), blank=True, max_length=255) override_password = models.CharField(max_length=73) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) Setting the password in forms.py: class UserUpdateForm(ModelForm): override_password = forms.CharField( label="Override password", max_length=8, strip=False, widget=forms.PasswordInput, ) class Meta: model = User fields = ['name', 'override_password'] view.py: class UserUpdateView(LoginRequiredMixin, AdminRequiredMixin, UpdateView): form_class = UserUpdateForm class Meta: model = User def get_success_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) def get_object(self): return User.objects.get(username=self.request.user.username) def form_valid(self, form): messages.add_message( self.request, messages.INFO, _("Info updated successfully") ) return super().form_valid(form) user_update_view = UserUpdateView.as_view() So right now it just saves in plain text. I have tried using make_password and then setting that in the password field, but then when I tried to use check_password, … -
Django weird symbols while downloading excel file
Django returning weird symbols while trying to download excel file file_name = 'data.xlsx' response = HttpResponse(open(file_name, 'rb'), content_type="application/xlsx") response['Content-Disposition'] = "attachment; filename=Report-{}.xlsx".format(datetime.now().strftime("%d.%m.%Y")) return response -
How to query only the pending interest and not interest that is already accepted/declined?
How to query only the pending interest and not interest that is already accepted/declined? Currently, i am able to query the number of interests that has been submitted. How can I query only the interest that has the status on pending and not accept/decline for my views? I tried to do total_interests = blog_post.interest_set.status.pending.count() but got AttributeError..'RelatedManager' object has no attribute 'status' models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class Interest(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) class InterestInvite(models.Model): ACCEPT = "ACCEPT" DECLINE = "DECLINE" PENDING = "PENDING" STATUS_CHOICES = [ (ACCEPT, "accept"), (DECLINE, "decline"), (PENDING, "pending"), ] interest = models.OneToOneField(Interest, on_delete=models.CASCADE, related_name="interest_invite") status = models.CharField(max_length=25, choices=STATUS_CHOICES, default=PENDING) views.py class BlogPostMixin(object): model=BlogPost class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() total_interests = blog_post.interest_set.count() context['total_interests'] = total_interests