Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'solvent' from partially initialized module 'api.views' in django rest api
I am using Django rest framework to do prediction on two strings and using celery to run inference. But I am getting error when trying to take solute and solvent from the result function into tasks.py file but I am getting error ImportError: cannot import name 'solvent' from partially initialized module 'api.views' My views.py file from .tasks import predictions @api_view(['GET']) def result(request): response = {} solute = request.GET.get('solute') solvent = request.GET.get('solvent') results = predictions.delay() response["interaction_map"] = (results[1].detach().numpy()).tolist() response["predictions"] = results[0].item() return Response({'result': response}, status=200) My tasks.py file @shared_task(bind=True) def predictions(self): mol = Chem.MolFromSmiles(solute) mol = Chem.AddHs(mol) solute = Chem.MolToSmiles(mol) solute_graph = get_graph_from_smile(solute) mol = Chem.MolFromSmiles(solvent) mol = Chem.AddHs(mol) solvent = Chem.MolToSmiles(mol) solvent_graph = get_graph_from_smile(solvent) delta_g, interaction_map = model([solute_graph.to(device), solvent_graph.to(device)]) return delta_g, torch.trunc(interaction_map) -
Is it possible to implement a GUI (written in Python) in Django so I can use that GUI in the browser?
I have made a programme with GUI written in Python that uses: (as input data) excel file pandas beautifulsoup requests and web-scraping: for collecting actual currency exchange rates SkPy API: for sending the good news to my friends via skype I'd like to know is it possible to somehow migrate it to Django, so I can use it by webpage instead of in Windows/Ios? As Django's APP, in the admin sub-page. If so, what would be needed? I'm so excited to do it !!! :) -
Django: Search products starting with query => product_name__starswith=query
Products model class Products(models.Model): product_name = models.CharField(max_length=120) Queryset Products.objects.filter(product_name__startswith=query) I want to find all the products starting with search query only. For example: When I search for ca it returns car car cover and when I search for car cover, it only returns car cover But I want it to return car in the second search as well. Is there any possible way to do it? Please help me. Thank you. -
Hosting Static Files on Amazon Web Services > Amazon Bucket - Django - PNG - CSS files
I need to host my static files on AWS in order to sort out some problems I have been having with my Django website. I have been trying to solve this on and off for about a year now while finishing up the rest of the website but now it is the last thing to do and I can't put it off any longer. I have looked at the documentation and looked at so many videos with no luck. Below is everything I have including code and my bucket file configuration that pertains to this problem. Everything that I currently have running should be hosting all my static files on my Amazon Bucket, however, it isn't. I'm not getting an error but when I 'inspect' on google they are all being hosted locally. I have followed so many tutorials and started from scratch so many times and nothing is seeming to work. Thank You so much in advance.What is wrong with the configuration below? Is MEDIA_URL affecting it? P.S. = The gallery folder I have in my bucket is for images that users upload and those images are successfully being hosted on AWS and working fine it's just the static. … -
Upgrading to Django 4.0.1 from Django 3.2.10 - "got both positional and keyword arguments for field" error message
I'm trying to update a Django project from version 3.2.10 to 4.0.1 When running the tests, I'm getting this error: File "/Users/akira/Projects/work/speedy/cash_flow/jobs/bank_account/process_flinks_transactions_job.py", line 63, in __init__ super(ProcessFlinksTransactionsJob, self).__init__(*args, **kwargs) File "/Users/akira/.local/share/virtualenvs/speedy-kJQJ8v9W/lib/python3.8/site-packages/django/db/models/base.py", line 446, in __init__ raise TypeError( TypeError: ProcessFlinksTransactionsJob() got both positional and keyword arguments for field 'name'. The code that's raising the error is: class ProcessFlinksTransactionsJob(Job): objects = ProcessFlinksTransactionsJobManager() def __init__(self, *args, **kwargs): kwargs.update({"name": ProcessFlinksTransactionsJob.__name__}) super(ProcessFlinksTransactionsJob, self).__init__(*args, **kwargs) How would I go about fixing this error? -
django inline formset for nested models
I have three models: Devices, Location and LocationMapping while LocationMapping is connecting Devices with Locations. I want to create DeviceForm but don't know how to add Location to it using inline formset. Is it possible with three models? class Device(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) class Location(models.Model): name = models.CharField(max_length=255) roomnumber = models.CharField(max_length=255, blank=True, null=True) building = models.CharField(max_length=255) class LocationMappings(models.Model): device = models.OneToOneField(Device, models.DO_NOTHING) location = models.ForeignKey(Location, models.DO_NOTHING) I thought about somethinglike LocationMappingFormSet = inlineformset_factory(Device, LocationMapping, form=LocationMappingForm, extra=1 ) LocationFormSet = inlineformset_factory(LocationMapping, Location, form=LocationForm, extra=1 ) but i didn't work out. -
In Django, how to reload specific button params in without reload the page
I am creating a method of likes for a social network type website, currently I can update the likes if I reload the entire page every time the user likes it, but as in the rest of the websites it does not have this effect I would like to eliminate the reload but I have not been able to, I tried an asynchronous call but it only works on the first element and I would not know how to proceed to eliminate this update method in the likes my html for each card <div class="media pt-3 pl-3 pb-1"> <a href="{% url "users:detail" post.user.username %}"> <img class="mr-3 rounded-circle" height="35" src="{{ post.profile.picture.url }}" alt="{{ post.user.get_full_name }}"> </a> <div class="media-body"> <p style="margin-top: 5px;">{{ post.user.get_full_name }}</p> </div> </div> <img style="width: 100%;" src="{{ post.photo.url }}" alt="{{ post.title }}"> <p class="mt-1 ml-2" > <a style="color: #000; font-size: 20px;" id="like_heart" data-id="{{ post.pk }}" data-url="{% url 'posts:likes2' %}"> <i class="{% if request.user in post.likes_users.all %} fas fa-heart {% else %} far fa-heart {% endif %}" id="success_like"></i> </a> <i id="value_like">{{ post.likes_users.count }}</i> </p> <p class="ml-2 mt-0 mb-2"> <b>{{ post.title }}</b> - <small>{{ post.created }}</small> </p> </div> my ajax call $(document).ready(function(){ // ajax for call in post $("#like_heart").on("click",function(e){ // e.preventDefault(); … -
Django REST Method Destroy getting 404 not found when sending from axios
I have been trying and searching alot but no one had this problem apparently. So the problem is that i am trying to send an axios request to delete with the correct api ur and key. But DRF Model.ViewSet does not find the function with appropriate PK. Backend This is my view.py file: class GigList(ViewSet): def destroy(self, request, pk=None): print(pk) Gig.objects.filter(user=request.user, id=request.id).delete() return Response urls.py: router = DefaultRouter() router.register('api', views.GigList, basename='user') Frontend This is the js file where axios executes: async deleteGig(id) { const response = await api.delete(`api/destroy/${id}` + `/`,TokenService.getLocalAccessTokenHeader() ); return response } Django outputs: Not Found: /api/destroy/17/ [09/Jan/2022 23:44:46] "DELETE /api/destroy/17/ HTTP/1.1" 404 8064 If anyone has an hint or solution to this, i would be grateful, thanks guys -
How to find how many objects reference the same foreign key in Django
I'm creating a simple web app that uses Django as its backend. Currently, I have two models: Toy and Attributes. A toy contains a reference to an attribute. My goal is to return an error to the frontend whenever an attribute is going to be deleted but is still referenced by a toy. For example, a train toy could have the attribute "black". When I go to delete black, I should get a not possible error, since "black" is still referenced by the toy train. How would I go about checking the number of references an Attribute has? -
Django ajax how to get object href and image link?
I am implementing ajax in my list views page. Now I am facing problems for rendering image and object href. How to get my object href link and image src link from ajax? here is my code: views.py: class PostJsonListView(View): def get(self, *args, **kwargs): print(kwargs) upper = kwargs.get('num_posts') lower = upper - 1 posts = list(Blog.objects.values('id','title','body','blog_header_image')[lower:upper]) posts_size = len(Blog.objects.filter(is_published='published')) max_size = True if upper >= posts_size else False return JsonResponse({'data':posts,'max': max_size},safe=False) .html <div class="card mb-4" id="card mb-4"></div> <script> const postsBox = document.getElementById('card mb-4') console.log(postsBox) const spinnerBox = document.getElementById('spinner-box') const loadBtn = document.getElementById('load-btn') const loadBox = document.getElementById('loading-box') let visible = 1 const handleGetData = () => { $.ajax({ type: 'GET', url: `/posts-json/${visible}/`, success: function(response){ maxSize = response.max const data = response.data spinnerBox.classList.remove('not-visible') setTimeout(()=>{ spinnerBox.classList.add('not-visible') data.map(post=>{ console.log(post.id) postsBox.innerHTML += `<div class="card-body"> <h2 class="card-title"><a href="">${post.title}</a></h2> </div>` }) if(maxSize){ console.log('done') loadBox.innerHTML = "<h4>No more posts to load</h4>" } }, 500) }, error: function(error){ console.log(error) } }) } handleGetData() loadBtn.addEventListener('click', ()=>{ visible += 3 handleGetData() }) </script> How to get object href so user can click an view the details page? also how to render image url? -
define fields of Django ModelForm class on instantiation
I want my website-users to quickly adjust just one attribute of my model objects in a view (with htmx) (to avoid creating tons of ModelForms just with other fields attributes) that's why I want to create a ModelForm where I can define the displayed form fields on instantiation of the form in the view function, the desired field will be passed as a 'fieldlist' parameter into the view function , somehow like that: class ModelForm(ModelForm): class Meta: model = Model fields = --> how to put the at the ModelForm-instantiation (with a request passed) "fieldlist" parameter here? def __init__(self, *args, **kwargs): fieldlist = kwargs.pop('fieldlist') super(ModelForm, self).__init__(*args, **kwargs) any hints? -
How to send Crypto payments (programmatically) gotten through coinbase commerce
i have successfully integrated coinbase commerce into my django app for receiving cryptocurrency payment from the users. However the site payment process involves receiving payment from a User A which is intended for User B into the site coinbase commerce wallet and then only after User B has completely handed over whatever was the value/asset been paid for, then the payment would go on to be forwarded finally to User B. But the issue is that coinbase commerce has no facility for sending payments. and though payment can be sent with a python api on COINBASE, they are two seperate things and the money/coin in coinbase commerce would not be accessible from COINBASE even if it the same user/profile on the platform. Please does anyone have a solution to this problem...even if it does not use coinbase commerce, the only requirement is that it uses a crypto payment gateway -
Ajax / Django / jQuery - autocomplete titles and remove when user deletes what was typed into input
(Reposted from Reddit) I am in the early stages of generating an autocomplete (I would love for it to be a drop-down from the input I'm using, right now it's divs that are being prepended), when a user begins typing (once >2 characters reached). I had a version that would somewhat-correctly show these results that it's pulling from a massive database after typing into the input has begun. But when I added the "else if" close to the bottom with the intention of removing all divs that have been added once the user starts deleting the typed-in phrase, nothing is coming up now. This is the implementation of my js file as it currently stands: $(document).ready(function() { $( "#movie_titles" ).keyup(function(){ var movie_titles = $('#movie_titles').val(); var has_typed = false; if (movie_titles.length > 2) { $.ajax({ url: '/get_movies', type: 'POST', data: {'movie_titles': movie_titles, csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: 'json', success: function(response) { // var len = response.length; has_typed = true; $('#movie_titles').empty(); console.log(response) // for (var i = 0; i < len; i++) { $('#result-part').prepend('<div class="movie-title">' + response.title + '</div>'); // $(this).val(''); return false; } }); console.log(movie_titles); } else if (has_typed && movie_titles.length <= 2) { $('#result-part').remove(); } }); }); Any ideas … -
Django passwords changing by themselves
I have a really weird issue, I use django authentication and I use django AbstractUser. The problem is passwords are changing by themselves, I'm not even able to track when this change occurs, even if the App is not used, once I try to login again I can't it tells me the password is wrong, How did I know that the password changed ? I compared the SHA code in database, since I always use "admin" as password for the app. I have some password configs in my settings but I doubt it is linked to them : REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'forms.api.serializers.PasswordResetSerializer', } # Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] this is my User model class User(AbstractUser): ''' model for user extends default django user ''' MALE = 1 FEMALE = 2 GENDER_CHOICES = ( (MALE,'Male'), (FEMALE,'Female') ) gender = models.PositiveIntegerField(choices=GENDER_CHOICES,null=True) email = models.CharField(max_length=256,unique=True,blank=True,null=True) receive_emails = models.BooleanField(default=True) objects = CustomUserManager() created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_date = models.DateTimeField(auto_now=True, blank=True, null=True) Can you please, if anyone has encountered this issue before, let me know and also if there is a solution to solve this. … -
Send csv files with data from db to email python
I have db and there is table called Users. id name last_name status 1 John Black active 2 Drake Bell disabled 3 Pep Guardiola active 4 Steve Salt disabled I would like to send to one email two csv files. The first one will be with name sucess.csv and there will be ID from the table, with status active, and the second one csv will be named failed.csv and inside will be ID with status disabled. Right now my code looks like this: def send_user_report(): logger.info('User report generating') user_data = {} user = Users.objects.values('id', 'status') buffer = io.StringIO() writer = csv.writer(buffer) writer.writerow([]) email = EmailMessage('Users report', body, to=settings.EMAIL_TEST) email.attach('sucess_report.csv', buffer.getvalue(), 'text/csv') email.send() -
Hosting Static Files on AWS - Amazon Bucket - Django
I need to host my static files on AWS in order to sort out some problems I have been having with my Django website. I have been trying to solve this on and off for about a year now while finishing up the rest of the website but now it is the last thing to do and I can't put it off any longer. I have looked at the documentation and looked at so many videos with no luck. Below is everything I have including code and my bucket file configuration that pertains to this problem. Everything that I currently have running should be hosting all my static files on my Amazon Bucket, however, it isn't. I'm not getting an error but when I 'inspect' on google they are all being hosted locally. Thank You so much in advance. P.S. = The gallery folder I have in my bucket is for images that users upload and those images are successfully being hosted on AWS and working fine it's just the static. This means the connection to the bucket is working fine. import django_heroku from pathlib import Path import os from django_quill import quill # Build paths inside the project like … -
Describe MS SQL database for Django legacy integration
I am trying to integrate a legacy DB (MS SQL 2012) into Django just to fetch data (no write operations). I have tried using the inspectdb management command but it only generates tables which don't have any foreign keys. I am fairly certain that the DB tables do not include foreign keys from a different DB (which is currently not supported by django). How do I go about getting all the attributes for each column/field in all of the tables so that I can create Django models on my own? Details that I'm looking for include (but are not limited to) : Column data type, All relational keys (Foreign, o2o, o2m), Max length, Max digits, Isblank, Isnull, Unique, Uniquetogether, Decimal places. -
How to post information from javascript TextInput into a django sqlite database?
I am completely new to website backends and am stumped on how to post information from a TextInput field created in Adobe Animate to a database. I would be able to do this no problem if the TextInput was part of an HTML form, but because it's javascript, I am lost. I've uploaded the project to my Github here: https://github.com/jeremyjed/SavetheDate and the site can be viewed on the repos page here: https://jeremyjed.github.io/SavetheDate/ I also have this page running on my local machine inside django. As you view that, the second to last slide has a TextInput labeled "addrs" and a submit button labeled "submit". Right now I have it so the animation continually loops on this slide to allow a user to input their data. Once the submit button is clicked the animation progresses to the last page. All I'm trying to do is to post the information populated in the TextInput field when the submit button is clicked and save it to django's database. I'm assuming this isn't too complicated, I just cant seem to get it to work. Any help would be really appreciated! -
Dj rest auth using JWT Token stored in HttpOnly cookies
I'm making a Django Rest Framework application with a JWT authentication with tokens stored in HttpOnly cookies. Authentication is performed via reading the access cookie. I'm using a dj-rest-auth library for this purpose, but I'm a little confused of the security aspect of such method. Knowing that having authentication data stored in cookies can be used to perform CSRF attack, how can one protect their web against such attacks for a specific case I've described above? All cookies are set to be SameSite=Lex. Do I need to also send X-CSRFTOKEN header obtained from the backend? That would mean that every request to the api will need to have that header. What should be the optimal setup having all those libraries? -
Django how to save value to model without being present on form post
I have the following Model/form/view: Model class Account(models.Model): username = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150) identifier_type = models.ForeignKey(IdentifierType, on_delete=models.SET_NULL, null=True) actflag = models.CharField(max_length=1, blank=True) created_date = models.DateTimeField(blank=True, null=True) comments = models.TextField(_( 'comments'), max_length=500, blank=True) priority_type = models.ForeignKey(PriorityType, on_delete=models.SET_NULL, null=True) deadline_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.name Form class PortfolioForm(forms.ModelForm): portfolio = forms.CharField(widget=forms.Textarea) class Meta: model = Account fields = ['name', 'comments', 'priority_type', 'deadline_date', 'identifier_type', 'portfolio'] View def portfolios(request): if request.user.is_authenticated: if request.POST: fm = PortfolioForm(request.POST) user = User.objects.get(username=request.user) if fm.is_valid(): messages.success(request, 'Portfolio has been created.') fm.save() return redirect('portfolios') else: fm = PortfolioForm() context = {"name": request.user, "form": fm} return render(request, 'portfolios.html', context) else: return redirect('login') The form works fine with posting via my template, however you will notice there are some fields within my model that are not in my form I would like to fill in automatically without the user having to fill in - for example username field I would like this to be current user that submits the form and also created_date would like the current date time the user has submitted the form. I tried to add the following to my view under if fm.is_valid(): attempting to save username as current user to the … -
Hosting Static Files on AWS - Amazon Bucket - Django
I need to host my static files on AWS in order to sort out some problems I have been having with my Django website. I have been trying to solve this on and off for about a year now while finishing up the rest of the website but now it is the last thing to do and I can't put it off any longer. I have looked at the documentation and looked at so many videos with no luck. Below is everything I have including code and my bucket file configuration that pertains to this problem. Everything that I currently have running should be hosting all my static files on my Amazon Bucket, however, it isn't. I'm not getting an error but when I 'inspect' on google they are all being hosted locally. Thank You so much in advance. P.S. = The gallery folder I have in my bucket is for images that users upload and those images are successfully being hosted on AWS and working fine it's just the static. This means the connection to the bucket is working fine. import django_heroku from pathlib import Path import os from django_quill import quill # Build paths inside the project like … -
django How do I print functions as they are called?
It's the best way I've found so far. https://pypi.org/project/Autologging/ from autologging import traced @traced class SocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): user = sociallogin.user print(user.email) raise Exception('test') However, this method only print the decorated class. Is there any way to print all the connected subclass functions when they are called? -
How to get data from config file (config.json) in real time in settings.py file in django
I have a project made in Django. I have only added social auth for login purposes. I want selected emails only to log in to the website. I used social-auth-app-django library for social auth and added a variable SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS to the settings.py file where it contains a list of all the emails permitted for logging in. My project directory looks something like this: project_parent/ ----project/ --------settings.py --------wsgi.py --------asgi.py --------urls.py ----app/ --------models.py --------views.py --------urls.py --------admin.py ----db.sqlite3 ----manage.py ----config.json Here is the config file: { "OAUTH2": { "WHITELISTED_EMAILS": [ "xyz@gmail.com", "abc@gmail.com", "efg@gmail.com", "lmn@gmail.com" ] } } In settings.py file I have loaded the config file like this: config = open('./config.json',) data = json.load(config) SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS = data['OAUTH2']['WHITELISTED_EMAILS'] I have made a webpage that takes the new mail id (need to add to the config file) and appends that particular mail id (or a list of mail ids) to the config.json file. But now the problem arises, the newly added mails don't reflect directly to the variable defined in the settings.py file. For that, I need to restart the code in order to get the latest config file. Every time I add a mail id, I need to restart the code. I thought to … -
Error NoReverseMatch at /contacto/perfil-contacto/1/
Estoy haciendo una agenda de contactos y tengo un problema a la hora de redireccionar a una url en la plantilla. Cuando quiero editar un contacto me aparece el siguiente error: NoReverseMatch at /contacto/perfil-contacto/1/ Reverse for 'actualizar_contacto' with arguments '('',)' not found. 1 pattern(s) tried: ['contacto/actualizar\-contacto/(?P[^/]+)$'] Donde el error en la plantilla es el siguiente: <a href="{% url 'contacto:actualizar_contacto' perfil.id %}"></a> La urls del archivo principal es esta: urlpatterns = [ path('admin/', admin.site.urls), path('', login_required(Inicio.as_view()), name='index'), path('contacto/', include(('MiApp.Contacto.urls','contacto'))), path('usuario/', include(('MiApp.Usuario.urls','usuario'))), path('accounts/login/', Login.as_view(), name='login'), path('logout/', login_required(logoutUsuario), name='logout'), ] Y en mi app tengo la siguiente url que corresponderia a donde quiero dirigirme, que seria la de perfil_contacto: urlpatterns = [ path('nuevo-contacto/', CrearContacto.as_view(), name='nuevo_contacto'), path('perfil-contacto/<str:pk>/', PerfilContacto.as_view() , name='perfil_contacto'), path('actualizar-contacto/<str:pk>/', ActualizarContacto.as_view() , name='actualizar_contacto'), path('eliminar-contacto/<str:pk>/', EliminarContacto.as_view(), name='eliminar_contacto'), ] Como se puede ver tiene la "pk" tanto en la url como en la plantilla. Si me pueden ayudar lo agradeceria, gracias. -
I want to get all the wallpapers who have similar name, tags to the wallpaper which is rendered
view.py def download(request, wallpaper_name): wallpaper = Wallpaper.objects.get(name=wallpaper_name) context = {'wallpaper': wallpaper} return render(request, 'Wallpaper/download.html', context) models.py class Tags(models.Model): tag = models.CharField(max_length=100) wallpaper model class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = models.ManyToManyField(Tags) HTML <ul> <li>{{wallpaper.name}}</li> {% for i in wallpaper.tags_set.all %} <li>{{i.tags}}</li> {% endfor %} url.py path('<wallpaper_name>/', views.download, name="download"), Like example the wallpaper I have choosen to download has tags nature and ocean so I want all the wallpapers who have this tag