Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can objects be reordered using django-sortedm2m?
A Collection object can contain several Item objects, and an Item object can be contained by several Collection objects. The items should be ordered in each collection. I am using django-sortedm2m: from sortedm2m.fields import SortedManyToManyField class Item(models.Model): pass class Collection(models.Model): items = SortedManyToManyField(to=Item) >>> item_1 = Item.objects.create() >>> item_2 = Item.objects.create() >>> collection = Collection.objects.create() >>> collection.items.set([item_2, item_1]) >>> collection.items.all() <QuerySet [<Item 2>, <Item 1>]> As expected, the order of items as they have been added is preserved. However, I want to reorder these elements, in the spirit of a "classic" model with ForeignKeyField and order_with_respect_to: collection.set_item_order([1, 2]). What is the best or simplest way to do that? -
Django : generate a file then save it in a FileField
I have a model Contract. When users create a new Contract, they only have to provide the name. Then, my code will generate a file, and save it in contract_file which is a FileField. For this, I have a static method for generating the file, then I overwrite the save method of django's Model. class Contract(models.Model): name = models.CharField(max_length=150, null=True) contract = models.FileField(upload_to = 'contrats/', blank=True, null=True) def save(self, *args, **kwargs): filename = self.generate_contract() f = open(filename, "r") self.contract.save(filename, f) return super(Refund, self).save(*args, **kwargs) @staticmethod def generate_contract(): filename = settings.MEDIA_ROOT + 'test.txt' f = open(filename, "w") f.write("content") f.close() return filename Unfortunately, this results in an Exception Value: maximum recursion depth exceeded while calling a Python object I suppose that when I call the FileField save method, it might somehow also call the Contract' save method. But I could not solve this problem. Does anyone have a method for performing this file generation then saving it ? -
Django values method - related objects in list [closed]
Hi help with values () method of queryset. When displaying related fields (Foreign key), the data is repeated, can this data be grouped? class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True, db_index=True) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='product_image', on_delete=models.CASCADE) image = models.ImageField(upload_to='img/models/') is_main = models.BooleanField() Example here This is how it is displayed [ {'pk': 1, 'title': 'Product 1', 'product_image__image': 'img/models/mod_wpYzlnm.png'}, {'pk': 2, 'title': 'Product 2', 'product_image__image': 'img/models/mod2_wEr0D2q.png'}, {'pk': 2, 'title': 'Product 2', 'product_image__image': 'img/models/mod_pPQqmjB_we175uR.png'}, {'pk': 10, 'title': 'Product 3', 'product_image__image': 'img/models/mod_3mTxkb9_z4lKV3l.png'}, {'pk': 10, 'title': 'Product 3', 'product_image__image': 'img/models/heart.png'} ] This is how it should be [ {'pk': 1, 'title': 'Product 1, 'product_image__image': 'img/models/mod_wpYzlnm.png'}, {'pk': 2, 'title': 'Product 2', 'product_image': [ {'image':'img/models/mod2_wEr0D2q.png'}, {'image':'img/models/mod_pPQqmjB_we175uR.png'} ]}, {'pk': 10, 'title': 'Product 3', 'product_image': [ {'image':'img/models/mod_3mTxkb9_z4lKV3l.png'}, {'image':'img/models/heart.png'} ]}, ] -
TweepError at / Unable to access file: No such file or directory when I use can
Hi I started a project which I use Django + tweepy When I wanna tweet with media I save my media in cdn my photo upload successfully on my cdn but tweepy say / Unable to access file: No such file or directory my code : tweet_photo = form.cleaned_data.get('tweet_photo') photo = cloudinary.uploader.upload(tweet_photo, public_id=clean_text) media = photo['url'] api.update_with_media(media, clean_text) Thanks for your helping -
What is the best practice for implementing hierarchical fields in models?
I have below model: class Flower(models.Model): name = models.CharField(max_length=30) country = # I don't know province = # I don't know What is the best practice for implementing hierarchical country and province fields in models? I want that the user can select some countries and provinces from the list, and later he can add or remove them. also when the user select for example Germany from the country field, only provinces related to Germany will show in the province select box field. The user is able to select some countries and provinces -
Django async testing: Cannot operate on a closed database
I need to test some async functions in django and I need to add som decorators in order to enable my async tests to access to the DB. But, it still shows Error Traceback (most recent call last): File "/Users/apple/.local/share/virtualenvs/backend-KucV-wUh/lib/python3.9/site-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/Users/apple/.local/share/virtualenvs/backend-KucV-wUh/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 274, in create_cursor return self.connection.cursor(factory=SQLiteCursorWrapper) sqlite3.ProgrammingError: Cannot operate on a closed database. @database_sync_to_async def create_user(): user = User.objects.create( username='username', ) user.set_password('password') user.save() @pytest.mark.asyncio @pytest.mark.django_db(transaction=True) class WebsocketTests(TestCase): async def test_not_authenticated(self): await create_user() ..... other async functions -
How can i get only text from CKEditors RichTextField in Python?
I have CKEditor and i need the pure text from it in serverside. I tried re.sub to strip tags but it fails when there are tables or images or links how can i avoid them. Thanks in advance. -
Docker auto reload not working on remote server
I've setup a Django project that runs in Docker. I want to have my dev environment on a remote server and have it auto reload as I change my files locally. I've set up remote deployment in Pycharm and it works fine. All local changes are reflected on my remote server, I can also see that files get changed inside the Docker container as I've setup a volume in my docker-compose file. However auto reloading is not working, and I cannot figure out why. -
Connect javascript function with User to add User details (in django)
I am trying to make a website where I have a pomodoro timer.Everything works fine, I have also added login, logout and registration functionalities but now I need to manipulate User data: I would like to make a small calendar, and clicking on a day the User would see the total amount of time he used the timer (on that day).I have no idea how to connect my javascript function with the User, and the django model documentation doesn’t help.Could someone help me showing some code examples or giving some useful links to use.Thank you ;) -
Why do I keep getting 403 Error using Nginx?
I am new to nginx so I am not sure I am understanding it right. What I am trying to is the following redirect: subdomain.domain.com -> subdomain.domain.com/something My config looks like this: server { listen 80; root /MyUser/django-app/example; server_name ~^(?<subdomain>.+).domain.com$; location ~ ^/$ { return 301 http://subdomain.domain.com/something$request_uri; } } Now when I go to subdomain.domain.com I am correctly redirected to subdomain.domain.com/something but I keep getting the 403 Error. When the redirection happens Gunicorn should check the urls.py from my django project and provide the correct view. I think I am missing something but I cannot figure out how to solve this. I can provide additional information if needed. -
Best way to deploy a django project to Azure Ubuntu VM
I have a django project and bitbucket as Git. I would like to deploy the django project to an Azure Vm (Ubunut 20.04). I was wondering can I use bitbucket pipelines to deploy to the VM. Or shall I conternize the Django application to store it on a registry and run the image on the VM. -
Cross queries in django
I have two models as below class Watched(Stamping): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE, default=None) count = models.PositiveIntegerField() class Link(Stamping): ... user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) url = models.CharField(max_length=256, default=None) watched = models.ForeignKey(Watched, null=True, blank=True, on_delete=models.CASCADE, default=None) ... A user can create a Link object and when some conditions are met, the object will be added to Watched. The Watched model contains objects created by different users. Now I want to filter the Watched class and grab only the objects created by the requesting user in the Link model but I don't know how I can achieve that. Any help will be appreciated. -
Getting an empty list when using model.objects.filter
I have my API in Django REST Framework: Here is my models.py: class myModel(models.Model): user_email = models.CharField(max_length= 200, null= False) Here is my views.py: class GetItemsByEmail(generics.ListAPIView): def get_queryset(self): email_items = self.request.query_params.get("user_email") if(email_items is not None): itemsReturned = myModel.objects.all().filter(user_email = email_items) return Response(data= itemsReturned) Here is my urls.py: url_patterns = [ path('users/account=<str:id>/items', GetItemsByEmail.as_view()), ] My Question: I am getting an empty list, getting nothing from making an API call to the above endpoint, although I know that there are items with that filter query. I want to get all the items in the database associated with a particular email? -
How do I troubleshoot JavaScript quantity control?
I am currently implementing a page where the price of the option appears when I select the option. The code I wrote shows that the price is 0 won when the quantity is 1 piece. Everything else works fine, but I have no idea where the problem is. Why is this a problem? If you could help me, I'd really appreciate it. " <div class=\"price_btn\">\n" + " <input type=\"button\" value=\"-\" class=\"minus_btn\">\n" + " <input style=\"width: 15%;\" type=\"text\" value=\"0\" class=\"number\" name=\"quantity\" id=\"quantity\">\n" + " <input type=\"button\" value=\"+\" class=\"plus_btn\">\n" + " </div>\n" + " <div class=\"total_p\" style='margin-top:30px; margin-left: -2px;'>\n" + " <p style=\"font-size: 18px;\">가격<strong name=\"price2\" id=\"price2\" class=\"price_amount\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\">" + 0 + "</strong>원\n" + " <input name=\"price2\" id=\"price2\"\>" + " </div>\n" + " </div>\n" + " </li>\n" + " </ul>" + " </div>" + "\n" + "\n" + " </div>" ; $("#selectOptionList").append(whtml) var checkText = $("#optionSelect option:selected").attr("disabled","disabled"); } $(document).ready(function () { $('.price_btn input[type="button"]').on('click', function () { var $ths = $(this); var $par = $ths.parent().parent(); var $obj = $par.find('input[type="text"]'); var val = $obj.val(); var $input = $par.find('input[id="price2"]'); var $price2 = parseInt($par.find('strong[name="price2"]').text().replace(/[^0-9]/g, "")); if ($ths.val() == '-') { if (val > 1) $obj.val(--val); $input.val($price2); } else if ($ths.val() == '+') … -
Memory issue with Django web app which is receiving frequent data from clients using XMLHttpRequest
I am developing a Django web-application to allows participants to have meeting online (I am using Jitsi for that). During meeting, the application tracks the voice activity (whether someone is speaking or not) using a JS library. So, whenever the application detects the sound, it sends the data with timestamp to server using FormData and XMLHttpRequest. I have included a snapshot of the code below. var fd = new FormData(); fd.append('csrfmiddlewaretoken', "{{ csrf_token }}"); fd.append('session',{{session.id}}); fd.append('user',{{request.user.id}}); fd.append('group',{{group}}); fd.append('strDate',ServerDate.now()); fd.append('activity',speak_time); var xhr = new XMLHttpRequest(); xhr.open('POST', '/vad_upload/', true); xhr.send(fd); I have tested the application with 30-50 people and in each test I observed an increased memory consumption on server. I have included a graph below as well showing server load. I assumed that it may be happening due to high frequency of data sent from client. However, the memory consumption is remaining same even after the activity when all clients are signed off and no data are sent from their side. Restarting the server seems to work at the moment. However, it is not feasible once the application is in use. Could you please share some information on this issue. Any input would be of great help. My Django server is … -
How to fix IntegrityError: FOREIGN KEY constraint failed
I created UserProfile model and when i go to django admin and trying to create/change profile it throws an error IntegrityError: FOREIGN KEY constraint failed. I am new to djnago so I don’t understand why i'm getting this error. users/models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length = 40, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) slug = AutoSlugField(populate_from = 'username', null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() class Meta: verbose_name = 'User' verbose_name_plural = 'Users' def __str__(self): return self.email def get_absolute_url(self): return reverse('profile', args=[str(self.slug)]) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete = models.CASCADE, null = True, db_constraint=False) avatar = models.ImageField(upload_to = 'avatar', default = "empty_avatar.jpg", blank = True, null = True) description = models.TextField(default = '', null = True) recipe = models.ManyToManyField(Dish, blank = True) slug = AutoSlugField(populate_from = 'user', null=True) class Meta: verbose_name = 'Профиль' verbose_name_plural = 'Профили' @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() recipe/models.py class Dish(models.Model): title = models.CharField(max_length = 50) dish_image = models.ImageField(upload_to = 'images') I think it is something wrong with ManyToManyField but i don't know what forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() … -
Add information to DB only after admin approval - Django
I built a site that users can add word and association how to remember the word to a database. However I don't want that the DATA will save automatic I want to add options that only after the approval of admin the word will add to the DB and other users will see it. how can do I do that? Thank you! -
Two model fields referring to each other - django rest
I want to change one of the existing field names in the Django model. But, for the backward-compatibleness, we'd like not to override the existing field with the new one, keep both of them for now. Is there any way to have multiple fields referring to the same database object? i.e Code right now: class NetworkPackage: name = models.CharField(unique=True, blank=False, null=False) inbound = models.CharField(unique=True, blank=False, null=False) ... I want to implement: class NetworkPackage: name = models.CharField(max_length=32, unique=True, blank=False, null=False) inbound = models.CharField(max_length=128, unique=True, blank=True) mobile = models.CharField(max_length=128, unique=True, blank=True) ... Basically, 'inbound' and 'mobile' should refer to the same field and the request could be sent either with 'inbound' field or 'mobile'. -
Django rest framework best practices
I was wondering what would be the best approach . I've been agonizing on what is the best way to accomplish a given task. It is a project with a react frontend and django rest framework backend. I am working on the backend with the django rest framework . Task: To query a user by their phonenumber which is stored as the username field. To add a user to a profile model and add an extra field which is required by the profile model To create the new profile with the user as the profiles user . e.g Profile Model: User - ForeignKey ExtraField - Charfield My question is which of these solutions is better . Should I build a url like this : domain/users/{phonenumber} and post the Extra field and query the user like this. def get_object(self): return get_object_or_404(User,username=self.kwargs['phonenumber']) user= get_object() or Should I post both the phonenumber and the extrafield and query the user from the backend like this. user = get_object_or_404(User,username=request.data.get('phonenumber') both work but which would be the best practice if it even matters at all. -
drf-yasg - read http_method_names from urls.py
I have a Settings subclass of APIView which has 2 methods. class Settings(APIView): def get(self, request, id=None): pass def post(self, request): pass In urls.py, I have the following, urlpatterns = [ path('account/settings/<str:id>', Settings.as_view(http_method_names=['get'])), path('account/settings/', Settings.as_view(http_method_names=['post'])), ] As you can see, I want id to be passed as a parameter in get method, but not in post method. drf-yasg, ideally should only show 2 methods on Swagger page, but it shows 4 methods. 1. GET for /settings/{id} 2. POST for /settings/{id} 3. GET for /settings/ 4. POST for /settings/ I have tried adding @action(methods=['GET']), @api_view['GET']. But it doesn't work. How do I tell drf-yasg to read allowed methods from http_method_names in urls.py. -
save() prohibited due to unsaved related object in inlineformetset_factory
Wondering why inlineformetset_factory couldn't unhide the FK('shoe') in child model? Although I find my way to demonstrate what I am looking for in form, still curious the reason for that and is there possible to solve it? Modles.py class Shoes(models.Model): Sur = [ ('Trl','Trail'), ('Rd','Road') ] nameS = models.CharField(max_length=20) surface = models.CharField(max_length=10,choices=Sur,default='Rd') milage = models.FloatField(max_length=10) brand = models.ForeignKey(Brands, on_delete=models.CASCADE) target = models.ManyToManyField(Targets) def __str__(self): return self.nameS class Runs(models.Model): date = models.DateTimeField(auto_now_add=True) # DateTimeField(default=timezone.now) target = models.ForeignKey(Targets, on_delete=models.CASCADE) mileage = models.FloatField(max_length=3) duration = models.DateTimeField(blank=True) pace = models.IntegerField(max_length=3) shoe = models.ForeignKey(Shoes, on_delete=models.CASCADE) def __str__(self): return self.date.strftime("%Y/%m/%d") Views.py (those were commented is the way I find) def create_run(request): RunFormSet = inlineformset_factory(Shoes, Runs ,fields= '__all__' ,extra=5 ,widgets={'duration':SelectDateWidget()} ,form=RunForm) formset = RunFormSet() if request.method == 'POST': formset = RunFormSet(request.POST,instance=formset.instance) if formset.is_valid(): formset.save() return redirect('/') # Optimal_Num = 6 # if request.method == 'POST': # # print(request.POST) # formSet = [RunForm(request.POST, prefix=i) for i in range(Optimal_Num)] # if any(form.is_valid() for form in formSet): # formSet.save() # return redirect('/') # else: # formSet = [RunForm(prefix=i) for i in range(Optimal_Num)] return render(request, 'Clothes/run_form.html',{ "Forms" : formset }) -
Can I buy a domain name from one service and host a web app on another service?
I bought a domain name from gandi.net .However, it is not the best to host a Django web app. I am considering to switch to heroku. Does anyone has tips or advices when hosting a Django web app? -
this code gives me TypeError: view must be a callable or list/tuple in the case of include()
from django.conf import urls from django.conf.urls import include, url from django.contrib.auth import views as auth_views from django.contrib import admin from cs243.view import login,index2,studentprofile,photo,postgrad,undergrad,srsec,sec,languages,projects from credentials.views import internships,contact,language urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', login), url(r'^index2/$', index2), url(r'^studentprofile/$', studentprofile), url(r'^photo/$', photo), url(r'^postgrad/$', postgrad), url(r'^undergrad/$', undergrad), url(r'^srsec/$', srsec), url(r'^sec/$', sec), url(r'^internships/$', internships), url(r'^languages/$', languages), url(r'^contact/$', contact), url(r'^projects/$', projects), url(r'^language/(?P<language>[a-z\-]+)/$', language), url(r'^auth/$'[enter image description here][1], 'cs243.view.auth_view'), url(r'^invalid/$', 'cs243.view.invalid_login'), url(r'^loggedin/$', 'cs243.view.loggedin'), url(r'^register/$', 'cs243.view.register_user'), url(r'^register_success/$', 'cs243.view.register_success'), ]enter image description here -
How can I fill a table view based on some calculous, resorting to django?
So I'm starting a django web application and I'm new using django... So please be patient with me. So, in my project I have two views: 1- a user profile; 2- a sort of a calculator, that can give several results at the same time according to the user input So, to start, here is my model.py: class Calanalisis(models.Model): sequence = models.CharField(max_length=120000) gc_content = models.DecimalField(decimal_places=3, max_digits=1000) def gc_content_cal(self): if self.sequence == True: gc_content= round((self.sequence.count('C') + self.sequence.count('G'))/len(self.sequence) * 100,1) return gc_content forms.py: class AddSequenceForm(forms.ModelForm): class Meta: model = Calanalisis fields = ('sequence',) views.py: def calc_sequence(request): sequence_items=Calanalisis.objects.filter(person_of=request.user) form=AddSequenceForm(request.POST) if request.method=='POST': form=AddSequenceForm(request.POST) if form.is_valid(): profile=form.save(commit=False) profile.person_of = request.user profile.save() return redirect('calc_sequence') else: form=AddSequenceForm() myFilter=SequenceFilter(request.GET,queryset=sequence_items) sequence_items=myFilter.qs context = {'form':form,'sequence_items':sequence_items,'myFilter':myFilter} return render(request, 'Add_Calc.html', context) And now I want to introduce gc_content_cal to be calculated in the table. When I introduce the sequence, the sequence appears in the table, however the gc_content_cal continues to be 0, like the image shows. Can someone help me please? -
Python - TypeError querying Solarwinds N-Central via Zeep SOAP
I am using zeep for the first time in Python3, to access XML data from N-central Solarwind and trying to get customer information but I am stuck on Settings parameter I am getting TypeError got an unexpected keyword argument 'Key' I have tried everything but it is giving me the same error, even tried with get_type() method but still getting same error from zeep import Client from zeep import xsd def customer_info(request): client = Client('http://server-name/dms/services/ServerEI?wsdl') # settings_type=client.get_type('ns0:Customer') # value = settings_type(Key='listSOs', Value='true') value={ 'Key': 'listSOs', 'Value': "true", } response =client.service.Customer_List(Username=USER,Password=PASS,Settings=value) response2 =client.service.Device_List(Username=USER,Password=PASS,Settings=xsd.SkipValue) return HttpResponse(response) This is written in its Docs Parameters: username - the MSP N-central username. password - the corresponding MSP N-central password. settings - A list of non default settings stored in a List of EiKeyValue objects. Below is a list of the acceptable Keys and Values. If not used leave null. (Key) listSOs - (Value) "true" or "false". If true only SOs with be shown, if false only customers and sites will be shown. Default value is false.