Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django signal not printing message in terminal
I'm trying to understand the signals and use it in my application. However, even though including this signal does not give me any error message, and from Django admin panel, I can actually add a movie successfully, I can NOT see the message 'movie created' printed in my terminal when this happens. Anyone could see why? Thank you so much for any help! models.py ... from django.db.models.signals import post_save class Movie(models.Model): name = models.CharField(max_length=30) description = models.TextField(blank=True) rating = models.IntegerField(default=0, blank=True, null=True) class MovieGenre(models.TextChoices): Action = 'Action' Horror = 'Horror' History = 'History' New = 'New' genre = MultiSelectField( choices=MovieGenre.choices, max_choices=3, min_choices=1 ) def average_rating(self): rating = self.movierate_set.aggregate(Avg('rating'))['rating__avg'] return rating class Meta: ordering = ["-upload_date"] def __str__(self): return self.name def create_movie(sender, instance, created, **kwargs): if created: Movie.objects.create(name=instance) print('movie created') post_save.connect(create_movie, sender=Movie) -
Hide readonly field on form if its value is None
I have typical django model form and I want to hide one readonly field if its value is None and show if it has any value. Also this field is declared in Admin class, not on form. class DjangoAdmin(admin.ModelAdmin): from = DjangoForm readonly_fields = ("my_field",) fieldsets = ( ("Title", { "fields": ("my_field",) } ) ) def get_my_field(): value = None if ...: value = 1 return value -
Django: Problem with ContentFile: String content is not downloaded completely
I'm quite new to using Django. As first project I wrote a little tool to create M3U8-Playlists. My problem is, that long playlists are not transferred completely. This is the stripped-down code: def create(request): # just a dummy filelist playlist = ["#EXTM3U"] + 5 * ["/home/pi/music/" + 5 * "äöü0123456789á/" + "xyz.mp3"] file_to_send = ContentFile("") for item in playlist: file_to_send.write("{}\n".format(item.replace("/home/pi/Music", r"\\raspberry\music").replace("/", "\\"))) response = HttpResponse(file_to_send, "audio/x-mpegurl") response["Content-Length"] = file_to_send.size response["Content-Disposition"] = f"attachment; filename=\"playlist.m3u8\"" # print some debug info print("lines:", len(playlist), "chars (no linebreaks)", sum([len(entry) for entry in playlist]), "filesize:", file_to_send.size) return response The problem seems to lie in the non-ascii chars in playlist entries (äöüá). When there are no such characters, the file is transferred intact. I assume that these are characters that use two bytes in UTF-8, but writing strings to the ContentFile like I do is probably not correct. -
One-to-one relationship with two models (fields) in Django to the current model
How to have one-to-one relationship with two models (fields) in Django (User and Product to be one-to-one together to Review)? So one user should have one review per product. Is there a built-in solution in Django models? Obviously having them both foreignkeys would be wrong as given here. from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): title = models.CharField(max_length=255) class Product(models.Model): title = models.CharField(max_length=255) class Review(models.Model): title = models.CharField(max_length=255) user = ForeignKey(User, on_delete=models.CASCADE) product = ForeignKey(Product, on_delete=models.CASCADE) -
How to limit prefetch record in django
In this, I deal with 2 tables: brand & product. so I've used prefetch_related to get related products for a particular brand with only minimum brand price. but the problem is when I have 2 products at the same price it selects both records so how to limit this? alternatives_data = Brand.objects.filter(category__category_slug = category_slug).prefetch_related( Prefetch('products', queryset=Product.objects.annotate( min_brand_price=Min('brand__products__product_price') ).filter( product_price=F('min_brand_price') ).order_by('product_id'))) -
Django & Celery: calling a Class function as a Celery task
I'm having a little conceptual trouble with setting a class based Celery task (Just a quick note, this is different as I am not inheriting from the celery.Task class). The bound app task is merely a class method. I have the following in my celery.py file: import os import celery from celery.schedules import crontab from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Wave.settings') app = celery.Celery('DjangoProject', include=['amq.v1.TaskRunner.demand', 'amq.v1.TaskRunner.periodic']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute='1,11,21,31,41,51', hour='*', day_of_week='*', day_of_month='*'), APIMiddelwareTasks().dispatch_bookings_fetch.s(), ) class APIMiddelwareTasks(): def get_middleware_class(self, *args, **kwargs): from django.conf import settings return MiddlewareAPIClass( headers={'Content-Type': 'application/soap+xml; charset=UTF-8'}, config=settings.middleware_config, debug=False ) @app.task(bind=True) def dispatch_bookings_fetch(self, *args, **kwargs): # This is the main call for the MiddlewareAPI wrapper class. The config in settings.py contains the parameters from both the sandbox and production workstations. # Setting sandbox to True will query the sandbox workstation, and setting debug to True will query known session dates and times. middleware = self.get_middleware_class() ... However, the above seems to throw the following error: AttributeError: 'dispatch_surfers_bookings' object has no attribute 'get_middleware_class' Would anyone know the best way to create a class based of multiple app tasks, with the ability to reference various self.methods() within that task? Should I just class this … -
Django many-to-many query matching all related fields
I have two models connected by a many-to-many relationship in django. class BuildingMapping(models.Model): name = models.CharField(max_length=1000, null=False) buildings = models.ManyToManyField( Building, related_name="mapping" ) class Building(models.Model): function = models.CharField( max_length=1000, blank=True, null=True ) Function is a string containing one or more identifier divieded by a "/" e. g. "1300", "1300/2200", "1300/2230/7500", ... I now want to perform a query that gets only BuildingMapping instances where the function for all Buildings is identical. I tried the following, but this will also return BuildingMapping instances where only one Building has "1300" as function. BuildingMapping.objects.filter(buildings__function="1300") Thanks! -
Django staticfiles files problems
i have problem with Django staticfiles. anyway everything works good but when i want change something in Css or in image or Js nothing is happening. in settings.py i have this # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') i have 2 folder of statics first is static and seccond one i get after manage.py collecstatic i get another folder (staticfiles) so even when i'm deleting both folder my website files not Brokening i need to restart my mac. plus i cannot change elements in css because i'm woking on both folder but nothing happend enter image description here P.S sorry guys for my english . i'm learning it :( <3 -
Jquery Elements in a webpage not loading on webpage on clicking browser back button
I have a html form page(page 1) from where I go to page 2 html page. In page 1 I have fields such as Resolution, on selecting particular resolution populates fields such as frame-width and height(with value) which is loaded using Jquery and is disabled (just to show) Similarly I have cascaded drop-downs. On submission of this form I get the results on the same page. Also I have given option to display the output on new page. But when I get back to the previous page from new page. Jquery Elements are not loaded. Only static elements in form are loaded. Resolution stays but frame width and frame-height is not loaded. Also output on same page is also gone. How can I get to previous page as per my submission made. I am using Django in Back-end. Index.html <p><label>Resolution:</label> <select id="resol" name="resol" class="ip" autocomplete="off"> <option disabled selected value> -- select an option -- </option> <option value="2K">2K</option> <option value="4KDCI">4KDCI</option> <option value="4KUHD">4KUHD</option> <option value="480p">480p</option> <option value="576p">576p</option> <option value="720p">720p</option> <option value="1080p">1080p</option> <option value="CIF">CIF</option> <option value="FWVGA">FWVGA</option> <option value="HVGA">HVGA</option> <option value="QCIF">QCIF</option> <option value="QVGA">QVGA</option> <option value="VGA">VGA</option> <option value="WVGA">WVGA</option> <option value="other">other</option> <option value="all">All</option> </select> </p> Jquery to display $('#resol').change(function () { var value = $(this).val(); //history.pushState(null,null,"#resolution"); … -
Django user group == another model's group
I just lost myself a little, and I'm stuck on this one. I have a model which has a group field : class CalendarGroups(models.Model): GRP_CALS = ( ('Grp1', 'Grp1'), ('Grp2', 'Grp2'), ('Test', 'Test'), ) name = models.CharField(max_length=155, choices=GRP_CALS, blank=True, null=True) def __str__(self): return self.name class Meta: ... class CalendarMaster(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) group = models.ForeignKey(CalendarGroups, on_delete=models.CASCADE) date_valid = models.DateTimeField(null=True, blank=True) I just want to check, if the User's group matches the Calendar group - some context will be rendered. I tried with: user_groups = request.user.groups.values_list('name', flat=True) calendar_groups = CalendarMaster.objects.all() {% if user_groups in calendar_groups %} But somehow, I cant manage it -.- PS.User groups are the same as CalendarMaster's -
Highlight word and send GET request
I've created a text field in a Django model. I want to highlight words when word is clicked. I've found this answer How can I adjust it to send a GET request to Django when a word is selected to receive JSON from other website API? Thanks in advance! $(function() { editTxt('#myTxt'); editTxt('#myTxtDiv'); $('span').live('mouseover', function() { $(this).addClass('hlight'); }); $('span').live('mouseout', function() { $(this).removeClass('hlight'); }); }); function editTxt(selector) { $(function() { var newHtml = ''; var words = $(selector).html().split(' '); for (i = 0; i < words.length; i++) { newHtml += '<span>' + words[i] + '</span> '; } $(selector).html(newHtml); }); } -
django condition aggregate foreign key by value
TL;DR I want to make the long annotated query (at the project object manager part below) more elegant and efficient, and able to recalculate it self after related object was updated. Background I'm building a market place - every customer should be able to create a project that contains parts. The parts are the objects up for pricing offers. Every part contains a status Enum field - so we could know if it up to bid or already in work. Im Using Python 3.8.1 Django-rest-framework 3.10.3 (django-url-filter 0.3.14)[https://github.com/miki725/django-url-filter] Postgres 12.1 The functionality I need Projects should be filtered by their contained parts status - with specific conditions. Update on the project status should update all related parts. Projects can be created, update and deleted with the same object manager. Part Model Only relevant parts of the code: class PartStatuses(Enum): Draft = "Saved but not published" PendingBID = "It's BIDing time!" Proposal = "All BIDs are set" PendingPO = "Waiting for vendor to approve PO" WorkInProgress = "Vendor has accepted a PO" OnItsWay = "The part is ready and now await to be delivered" Delivered = "Delivery process has ended" Disputed = "Open for Dispute" Closed = "Part has received" Paid … -
Get an object id from HTML in in request.POST
I have an user with list of tasks that he can add. I want to give him ability to delete those tasks, or mark as done. The problem is that my solution is working only when user has one task, because of non-unique id's problem Is there any way to pass the id to html so that it will be easily accesible in views? Thank you! This is my current code {% for task in tasks %} <form id='is_checked' method='POST' action="{% url 'mark_as_done'%}" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group-text"> <input type="hidden" id="id_checked" value="{{task.id}}" name = "id_checked"> </div> </form> <form class="input-group" action="{% url 'delete_task'%}" method='POST' enctype="multipart/form-data"> {% csrf_token %} <div class="input-group-prepend"> <div class="input-group-text"> <input onChange="document.getElementById('is_checked').submit()" type="checkbox" {% if task.is_done %}checked{% endif %}> </div> </div> <h7 type="text" class="form-control">{{task}}</h7> <input type="hidden" id="id" value="{{task.id}}" name = "id"> <button type="submit" class="input-group-append btn btn-danger">Delete</button> </form> {% endfor %} And in views: def delete_task(request): if request.method == 'POST': task = Task.objects.get(pk=request.POST['id']) task.delete() return redirect('tasks') @login_required() def mark_as_done(request): if request.method == 'POST': task = Task.objects.get(pk=request.POST['id_checked']) task.is_done = True task.save() return redirect('tasks')``` -
Django REST: Problem with AUTH_USER_MODEL importing
I'm following this tutorial and trying to create custom user for REST-API. settings.py: INSTALLED_APPS = [ # blah blah 'courses', ] AUTH_USER_MODEL = 'courses.CustomUser' I have django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'courses.CustomUser' that has not been installed project tree: - django-project - courses - models.py models.py: class CurstomUser(AbstractBaseUser): username = None first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(max_length=254, unique=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [USERNAME_FIELD, 'first_name', 'last_name'] role = models.CharField(max_length=2, choices=UserRole.choices, null=False) def __str__(self): return '{} {}'.format(self.first_name, self.last_name) What's the problem? It seems I've set up AUTH_USER_MODEL correct way -
Query ManyToMany relationship Django
Hey everyone I want to query a manyToManyField from my database it seems that it doesn't work. I would like to get from the database model the list of all framework incompatibility. But when I do a query, I get nothing from that. Here is my models: class Framework(models.Model): name = models.CharField(max_length=200) language = models.ManyToManyField(Language) version = models.CharField(max_length=20) typeOfFramework = models.ForeignKey(TypeOfProgram, on_delete=models.CASCADE) pros = models.ManyToManyField(Pro) nombreAvantage = models.IntegerField(default = 0) cons = models.ManyToManyField(Con) nombreDesavantage = models.IntegerField(default = 0) additionalInformation = models.ForeignKey(web,blank=True,null=True ,default = None ,on_delete=models.CASCADE) incompatibility = models.ManyToManyField("self",blank=True) def __str__(self): template = '{0.name} {0.version} {0.typeOfFramework} {0.nombreAvantage} {0.nombreDesavantage} {0.additionalInformation}' return template.format(self) def getLanguage(self): return ", ".join([p.name for p in self.language.all()]) def getPros(self): return ", ".join([p.advantage for p in self.pros.all()]) def getCons(self): return ", ".join([p.disadvantage for p in self.cons.all()]) def getIncompatibility(self): return ", ".join([(p.name + ' '+ p.version) for p in self.incompatibility.all()]) def __iter__(self): return [ self.name, self.language, self.version, self.typeOfFramework, self.pros, self.cons, self.additionalInformation ] class DataPro(models.Model): advantage = models.CharField(max_length=200) def __str__(self): template = '{0.advantage}' return template.format(self) class DataCon(models.Model): disadvantage = models.CharField(max_length=200) def __str__(self): template = '{0.disadvantage}' return template.format(self) class Database(models.Model): name = models.CharField(max_length=200) version = models.CharField(max_length=20) pros = models.ManyToManyField(DataPro) nombreAvantage = models.IntegerField(default = 0) cons = models.ManyToManyField(DataCon) nombreDesavantage = models.IntegerField(default = 0) … -
How to send value in javascript to django
I try to get value in django from javascript but it's none value in some variable. template.html <script> $(document).ready(function () { first(); $('#btnAdd').click(first); }); var choices = ["one", "two", "three"]; function first() { var id = $('#cover div').length + 1; var wrapper = $("<div id=\"field" + id + "\" class='row info'><p></p>"); var category = ""; category = "<div class='col-md-2'><select class='form-control' name=\"category" + id + "\">"; for (i = 0; i < choices.length; i = i + 1) { category += "<option value='" + choices[i] + "'>" + choices[i] + "</option>"; } category += "</select></div>"; var product = $("<div class='col-md-5'><input type='text' id='tags' name=\"product" + id + "\" class='form-control' size=40 placeholder='ชื่อสินค้า' required/></div>"); // สร้าง input wrapper.append(category, product); $('#cover').append(wrapper); $(wrapper).find("input[name^='product']").autocomplete({ source: "/autocomplete_product?category", minLength: 2, }); } views.py product = request.GET['term'] category = request.GET['category'] I try to print request.GET, it show category and term variable. The term variable is normal (there is value) but category is null. I have question how to I send category to django. -
django.db.utils.IntegrityError: NOT NULL constraint failed: BookApp_book.publisher_id while updating models with fake data
I am trying to populate my models using some fake data generated through faker in my django project. I have created three models Publisher, Author, and Book. The migrations are done correctly and the models are created successfully. I am able to add the data to the models through admin interface, but when i try to populate the models through fake data i am getting the following error.django.db.utils.IntegrityError: NOT NULL constraint failed: BookApp_book.publisher_id I am not able to figure out what is the mistake. Here is my models.py from django.db import models # Create your models here. class Publisher(models.Model): ''' Publisher class model with name,country,email,website ''' name = models.CharField(max_length=25) country = models.CharField(max_length=25) website = models.URLField() def __str__(self): return self.name class Author(models.Model): ''' Author model with name,contact,email,age,location ''' author_name = models.CharField(max_length=25) age = models.PositiveSmallIntegerField() email = models.EmailField() # method for string representation of the class def __str__(self): return self.author_name class Book(models.Model): ''' Book model with title,pages,author,publisher,publication_date ''' title = models.CharField(max_length=100) pages = models.PositiveSmallIntegerField() author = models.ManyToManyField('Author') publisher = models.ForeignKey(Publisher,related_name='publisher',on_delete=models.CASCADE) publication_date = models.DateField() # method for string representation of book class def __str__(self): return self.title populate_bookapp.py import os # set the default environment to the projects settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BooksProject.settings') import django django.setup() … -
Django Website Built using Python 3.7.6 + Django 3.0.3 + Pandas 1.0.1 Hangs on Apache 2.4.41 due to Pandas 1.0.1
I have build a basic Website using Python 3.7 + Django 3.0.0 + MySQL 8.0.18 + Pandas 1.0.1. This site works very well using py manage.py runserver on my local environment. However, as soon as I deploy it on Apache 2.4.41 configured on Windows 10 Server. The site starts giving 408 error. Further this environment configured Apache(2.4.41) + mod_wsgi(mod_wsgi-4.7.1+ap24vc15.dist-info) + Python(3.7.6)+ django(3.0.3) + Pandas (1.0.1). On further debugging I have observed that imports from pandas are the root cause of the issue. Please code from model.py for your reference - from django.db import models, connection # from pandas import DataFrame # from pandas import concat, to_datetime, to_numeric **# Un-commenting above two lines cause the issue** # Create your models here. class ISMADates(models.Manager): def date_list(self): with connection.cursor() as cursor: cursor.execute("select date_id, date from master_date order by date_id desc LIMIT 10;") result_list = cursor.fetchall() # print(result_list) return result_list However as per my understanding pandas should work seamlessly with Django. And this combination is quite widely used. Please suggest the next steps to proceed further. -
How to load javascript file after ajax sucess in django
im working with ajax and trying to load external javaScript file after ajax success. So far what i have is this $.ajax({ url: "{% url 'app:cat_data_for' %}", type: "POST", async: false, data: {cat_data: cat_data,csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function (data) { $.getScript("{% static 'type.js' %}"); }); But It's not working. How to do this. Thanks in advance. -
URL management with Django, GraphQL, Apollo and VueJS
As said in the title, I'm using Django, GraphQL, Apollo and VueJS in my project. I'm developping it as a SPA (Single Page Application). Everything works fine, until I hit the F5 button and refresh the page. Indeed, it shows an unknown page. The thing is it is VueRouter that is managing the SPA and it works fine. But when I press F5, that is Django that tries to serve a page for the current URL and since it doesn't know it, it can't serve the appropriate page. I know I can set the VueRouter 'history' mode, which I did, and add a URL to Django that serves index.html whatever the URL is. My problem is the following : When I'm on a particular form view (i.e : a User form view) my URL is the following : http://localhost:8000/user Since I'm using GraphQL for my API, the retrieved data is not based on the URL. In fact, that is my VueJS component that says : Hey Apollo, run that GraphQL to retrieve the User I want. So when I refresh, yes it serves the User form view..but empty. The question is : How could I solve this ? For clarification … -
Editing button in the wrong form when editing a manytomany field
I am trying to edit a ManyToMany relation field and I am using ModelForm in my forms.py and I am using Createview in my views.py. In my forms.py file I am using ModelMultipleChoiceField for the editing of the ManyToMany relation from the 'participant' field to Person model. The problem is that when the template render the form, it puts the editing button at the last field, not the one that I want to edit. for example: model=Activity participant=ModelMultipleChoiceField(queryset=Activity.objects.all()) fields=['activity_name','project','participant','min_stage_area'] this will put the editing button right behind the 'min_stage_area' form, not the 'participant' form where I want it. how do I solve this? views.py: class CreateTour(CreateView): form_class=CreateTourForm template_name='artdb/createtour.html' def get_context_data(self,**kwargs): context=super(CreateTour,self).get_context_data(**kwargs) return context def form_valid(self): response=super(CreateTour,self).form_valid() self.object.project=self.form.cleaned_data['project'] return response forms.py: class CreateTourForm(ModelForm): class Meta: model=Activity participant=ModelMultipleChoiceField(queryset=Activity.objects.all()) #person_instance.first_name.add(activity_instance) fields=['activity_name','project','participant','min_stage_area'] models.py: class Activity(models.Model): activity_name=models.CharField(max_length=200,default='no name') project=models.ForeignKey(Project,on_delete=models.CASCADE,default=1) participant=models.ManyToManyField(Person) min_stage_area=models.IntegerField(default='2') light_requirements=models.CharField(max_length=200,default='no requirements') sound_engineer=models.CharField(max_length=200,default='not needed') comment=models.ManyToManyField(Comment) def __str__(self): return self.activity_name class Meta: ordering = ('activity_name',) class Person(models.Model): SALARYTYPE=(('None','N'),('Faktura','F'),('Lön','L')) first_name=models.CharField(max_length=200,default='firstname') last_name=models.CharField(max_length=200,default='lastname') # role=models.ManyToManyField(Role) mail=models.EmailField(default='yourname@gmail.com') homepage=models.CharField(max_length=200,default='www.yourhomepage.com') phone_number=PhoneNumberField(default='+46707305134') street_address=models.CharField(max_length=200,default='streetAdress') zipcode=models.CharField(max_length=200,default='99999') city=models.CharField(max_length=200,default='Göteborg') country=models.CharField(max_length=200,default='Sweden') payment=models.CharField(max_length=10,choices=SALARYTYPE,default='none') comment=models.ManyToManyField(Comment) def __str__(self): return "%s %s" % (self.first_name,self.last_name) class Meta: ordering = ('first_name','last_name') template: {% extends "artdb/index.html" %} {% block ct %} <form method="post">{% csrf_token %} <div class="input-group"> {% for fr in formset %} {{fr}} … -
Reverse Url from slug with Persian or arabic languages in Django
hi i want to reverse url from slug in model i have slug : slug = models.SlugField(max_length=200, unique=True, allow_unicode=True) and for get absolute url : def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) and in settings.urls : urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls', namespace='shop')), ] and in shop.urls : app_name = 'shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), ] and value for my slug is : slug="گالری-شلوار" now i get error : Reverse for 'product_list_by_category' with arguments '('گالری-شلوار',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/$'] -
Django Admin - call change_view for inline
I am currently developing an application in Django. In the Admin part, I would like to exclude the "groups" part in the modification view, using the "change_view" method Here is the error returned: Information: I have an extended user table. In addition the error indicates that I can try with "user_permissions", but after testing it tells me again that I can use "groups" ... So it's not a naming problem Here is the code: # ADMIN # class UserExtendInline(admin.StackedInline): model = UserExtend max_num = 1 fk_name = 'user' can_delete = False fields = ('user','offer', 'valid_payments') class AccountsUserAdmin(UserAdmin): inlines = (UserExtendInline,) list_display = ('email','first_name','last_name','Formation_Souscrite','last_login','Paiement_Valide','is_active') readonly_fields = ('email', 'last_login', 'date_joined') def get_inline_instances(self, request, obj=None): if not obj: return list() return super(AccountsUserAdmin, self).get_inline_instances(request, obj) def Formation_Souscrite(self, obj): user_extend = UserExtend.objects.filter(user=obj).prefetch_related('offer') user_extend = user_extend[0] if not user_extend.offer is None: return user_extend.offer.name else: return "Aucune" def Paiement_Valide(self, obj): return UserExtend.objects.get(user=obj).valid_payments def change_view(self, request, object_id, extra_context=None): self.exclude = ['groups'] return super(AccountsUserAdmin, self).change_view(request, object_id, extra_context) Paiement_Valide.boolean = True # unregister old user admin admin.site.unregister(User) # register new user admin that includes a UserProfile admin.site.register(User, AccountsUserAdmin) admin.site.unregister(Group) Thank you for your reply -
Using live_server fixture in pytest: Site cannot be reached
I am trying to run selenium tests with pytest-django for my django app. Pytest-django provides a fixture called live_server. I am supposed to get the URL with live_server.url. Now when I try to visit live_server.url it opens a browser but then the browser shows that the site cannot be reached. This is the not-working code I am trying to run: @pytest.mark.django_db class TestAdmin(): @pytest.fixture def setup(self): global browser browser = webdriver.Remote( command_executor='http://selenium:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME, ) browser.implicitly_wait(5) yield browser.quit() def test_user_can_visit_website_with_chrome(self, live_server, setup): """Website is reachable in Chrome browser. """ browser.get(live_server.url) assert 'mywebsite' in browser.title The following code works if I use djangos inbuilt test runner: class AdminTest(BaseTestCase): def test_login(self) self.selenium.get(f"{self.live_server_url}/admin") path = urlparse(self.selenium.current_url).path self.assertEqual('/admin/', path) So with django's inbuilt live_server_url it visits my localhost without complaining. But I need this in pytest and I don't really want to mix both syntaxes. Reading the documentation it only says: live_server This fixture runs a live Django server in a background thread. The server’s URL can be retrieved using the live_server.url attribute or by requesting it’s string value: unicode(live_server). You can also directly concatenate a string to form a URL: live_server + '/foo. As I understand this it should work with the code that … -
Django ORM : Select rows from table A if it has the same id(FK) in the table B, where the rows in B are selected if it satisifies a condition:
I have table hospitals and other table departments. I need to do a search operation based on the city. When the user selects the city and types the department, it should check for hospitals in the hospital's table working in the user given city and then check in the department's table whether any of those hospitals are there in the table with the user given department. How do I do this with Django ORM? class HCSProfile(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) fname = models.CharField(max_length=255, blank=True, null=True) lname = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) class HCspeciality(models.Model): hospital = models.CharField(max_length=255, blank=True, null=True) speciality = models.CharField(max_length=255, blank=True, null=True) hospital_id = models.ForeignKey('HCSProfile', on_delete=models.CASCADE)