Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
BeautifulSoup4. How to follow such links and then parse the content in them?
For starters, i'm new in Python. I want to iterate over an each title link in my article list, follow each title link and then scrape the data on each of these webpages. But the problem is that the title links have an address like https://qwerty.com/review/first-news-article/ https://qwerty.com/review/second-news-article/ https://qwerty.com/review/third-news-article/ Again, i want to stay on each of the link like these, scrape some data, and then again go to the next article, follow the next title link, scrape some data..So, how can i do that in Python? I need to tell my program that I want to stay on the page that I went to by clicking on the article title, and then parse the data from that page.. but as a person who is not very experienced in data parsing, I don't know how. I will be glad if you help me, thanks! :) My code: def scrape(request): website_url = requests.get("https://loudwire.com/news/").text soup = BeautifulSoup(website_url, "html.parser") articles = [] excarr = [] img = [] mysrcset = [] links = soup.find_all('h2', {'class': None}) excerpt = soup.find_all('div', {'class': 'excerpt'}) myimg = soup.find_all('img', {'class': 'attachment-rc_post_thumbnail size-rc_post_thumbnail wp-post-image'}) for image in myimg: img.append(image.get('src')) srcset = image.get('srcset') mysrcset.append(image.get('srcset')) print(srcset) for l in links: print(l.text) articles.append(l.text) … -
Django Model Admin Not Accepting list_display values
I have These two models: class Transaction(models.Model): store = models.ForeignKey(Store, on_delete=models.DO_NOTHING) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) amount = models.DecimalField(max_digits=9, decimal_places=2) cc_type = models.CharField(max_length=3, choices=CC_TYPES) cc_transaction_id = models.CharField(max_length=200) trans_date = models.DateTimeField() qty = models.IntegerField() def __str__(self): return F'{self.store.title} - {self.cc_transaction_id} - {self.amount}' class Meta: unique_together = ('cc_type', 'cc_transaction_id') class Ticket(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.DO_NOTHING) amount = models.DecimalField(max_digits=9, decimal_places=2) ticket_id = models.CharField(max_length=200, unique=True) def __str__(self): return F'{self.ticket_id} - {self.amount}' and these ModelAdmins: @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): list_display = ['amount', 'cc_type', 'cc_transaction_id', 'user', 'store'] list_display_links = ['amount'] search_fields = ['cc_transaction_id', 'store__title', 'user__username'] @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): list_display = ['ticket_id', 'amount', 'transaction__qty'] list_display_links = ['ticket_id'] search_fields = ['ticket_id', 'transaction__cc_transaction_id', 'transaction__user__username'] It get an error when I try to start the runserver saying: <class 'Sales.Stores.admin.TicketAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'transaction__qty', which is not a callable, an attribute of 'TicketAdmin', or an attribute or method on 'stores.Ticket' The list_search seems to resolve fine but the list_display does not. I'm doing something similar in the TransactionAdmin and everything seems to be fine. -
ProgrammingError at /admin/blog/blogcomment/
enter image description here LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_blogcomment" -
ModuleNotFoundError: No module named 'django' problem in vs code
I have installed virtual environment via pip install pipenv for my django project in vs code. Although I had successfully installed virtual environment and django(3.0.5) , but when I tried to python manage.py runserver then it throw me an error. It simply says that it was unable to find any module called django(but when I typed django-admin --version it shows that I had django installed and it's version is 3.0.5). In my cmd i got the following message: C:\Users\Ahnaaf Al Rafee\POLLSTAR_PROJECT>"C:/Users/Ahnaaf Al Rafee/.virtualenvs/POLLSTAR_PROJECT-oW8GrevN/Scripts/activate.bat" (POLLSTAR_PROJECT) C:\Users\Ahnaaf Al Rafee\POLLSTAR_PROJECT>python manage.py runserver python: can't open file 'manage.py': [Errno 2] No such file or directory (POLLSTAR_PROJECT) C:\Users\Ahnaaf Al Rafee\POLLSTAR_PROJECT>cd pollstar (POLLSTAR_PROJECT) C:\Users\Ahnaaf Al Rafee\POLLSTAR_PROJECT\pollstar>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (POLLSTAR_PROJECT) C:\Users\Ahnaaf Al Rafee\POLLSTAR_PROJECT\pollstar>python manage.py runserver 8081 Traceback (most recent call last): File … -
Error: Cannot find module 'E:\python project\react-scripts\bin\react-scripts.js'
I want to just integrate Django Reatcjs but when I run "npm run build" then this error occurs. but the magic is when I build just only reactJs project then it will build the project. but with Django can't run. I hope anybody already finds this problem solution. 'ReactJs\djangoReactJs\reactapp\node_modules\.bin\' is not recognized as an internal or external command, operable program or batch file. internal/modules/cjs/loader.js:983 throw err; ^ Error: Cannot find module 'E:\python project\react-scripts\bin\react-scripts.js' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15) at Function.Module._load (internal/modules/cjs/loader.js:862:27) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) at internal/main/run_main_module.js:18:47 { code: 'MODULE_NOT_FOUND', requireStack: [] } npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! reactapp@0.1.0 build: `react-scripts build` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the reactapp@0.1.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Flash\AppData\Roaming\npm-cache\_logs\2020-04-23T06_27_42_378Z-debug.log -
Show month name instead of month number (fetched from db) in django model choice field
Column acct_per_num in table SAPAdjustment contains the month number. The following code gives a dropdown with unique month numbers (1,2,3) present in column acct_per_num in table SAPAdjustment but I want month names (January, February, March) instead of month numbers (1,2,3). forms.py class SAPReconForm(forms.Form): month = forms.ModelChoiceField(queryset=SAPAdjustment.objects.values_list('acct_per_num',flat=True).distinct(), empty_label=None) models.py class SAPAdjustment(models.Model): acct_per_num = models.IntegerField( blank=True,null=True, verbose_name =_('Month'),help_text=_('Month')) -
NoReverseMatch in Django after create Object
After create Object without template, I am trying to return tu the same list view but it send the reverse match error. This is my code: Function to create an object from other model: def pieza_fast_create(request, id_reporte): template_name = "metalitec/reportes_detalle.html" context_object_name = "obj" reporte = Reporte.objects.get(id=id_reporte) pieza=Pieza.objects.create(reporte=reporte, descripcion="PIEZA 1") piezas = Pieza.objects.all() return render(request, template_name, {'id_reporte':id_reporte,'reporte':reporte, 'piezas':piezas}) Current View: class ReporteDetalleView(LoginRequiredMixin, generic.TemplateView): model = Reporte template_name = "metalitec/reportes_detalle.html" context_object_name = "obj" #login_url = "bases:login" def get(self, request, *args, **kwargs): id_reporte = kwargs['id_reporte'] reporte = Reporte.objects.filter(id=id_reporte) piezas = Pieza.objects.filter(reporte__id=id_reporte) return render(request, self.template_name, {'id_reporte':id_reporte, 'reporte':reporte, 'piezas':piezas}) Urls: path('reportes/piezas/fast/<int:id_reporte>',pieza_fast_create, name='pieza_new_fast'), path('reportes/detalle/<int:id_reporte>',ReporteDetalleView.as_view(), name='reporte_detalle'), error: Reverse for 'pieza_new_fast' with arguments '('',)' not found. 1 pattern(s) tried: ['metalitec/reportes/piezas/fast/(?P<id_reporte>[0-9]+)$'] Thanks in advanced. -
Django db model alternative in node js
I have a model in Django DB in python. id = models.BigAutoField(db_column='xxxxxxxxx', primary_key=True) # 1 xxxxxx = models.ForeignKey('xxxxx', db_column='xxxxxx', blank=True, null=True, on_delete=models.DO_NOTHING) # 2 xxx_name = models.CharField(db_column='xxxxxx', max_length=100, blank=True, null=True) # 3 state = models.CharField(db_column='State', max_length=300, blank=True, null=True) # 4 class Meta: managed = False db_table = 'xxxxxxx' Which is dynamically creating join query or my SQL query based on a criteria selected_service_centres = class_name.objects.using('xxxxxx').only('id', 'xxxxx', 'xxxxx', 'address', 'xxxxx').filter(**conditions_query_dict).distinct() Is there any way I can create the same thing in node js. Is there any module which will work the same as Django DB. -
Django Static Files not Loading on Heroku, GCS deployment
So, I have created a django application and deployed it with Heroku. Static files (as well as media) are served by a GCS bucket. I am currently having a problem loading all of my static files. Notably, the png files are not loading, but everything else is. The png file requests return a 403 error, but the rest of the files (css, js, etc.) load fine. Furthermore, jpg images that were uploaded via media are returned without error. I have to assume that this is a GCS problem, but I'm not entirely sure of that. I have tried everything in including assigning permissions to my service agent, creating another service agent, and recreating another bucket with the same data. I have not had this problem when using GCS buckets with applications running on Google App Engine or GKE. Any point in the right direction would be great. This is the relevant part of my settings file. Note that I put the django_heroku.settings(locals()) call above this block of code intentionally, because it overrides these settings. DEBUG = False django_heroku.settings(locals()) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'hello-world' GCS_URL = 'https://storage.googleapis.com/' STATIC_URL = '{}/{}/static/'.format(GCS_URL, GS_BUCKET_NAME) MEDIA_URL = '{}/{}/media/'.format(GCS_URL, GS_BUCKET_NAME) STATIC_ROOT = … -
how do I store an image in views file in Django
I am making a Django website where I need to display images selected by user. These are the things I've done: Html form for image: <form action="" method="POST"> {% csrf_token %} <div class="form-group"> <label >Article Logo</label> <input type="file" class="btn btn-primary" name="article_image"> </div> <input type="submit" class="btn btn-success"> </form> models.py class Content(models.Model): article_image = models.ImageField(upload_to = 'media', null=True) views.py def submit_article(request): if request.method == 'POST': a_image = request.FILES['article_image'] new_article.article_image = a_image new_article.save() I've added below code to settings.py to specify media directory: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Added below code to urls.py of the website: urlpatterns = [ path(r'admin/', admin.site.urls), url(r'', include('logio.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The form is not able to add images to the media folder. If I'm adding images through the admin panel it works. Thanks in advance.... -
How can I dispaly more than one (different) model objects to one tempate django
I want to dispaly both models object in my index.html template, but its not working.. models.py enter image description here views.pyenter image description here -
why wappalyzer doesn't detect my site and my site technologies?
I've created a webpage with Django and python programming language. while I click on wappalyzer extension, It only shows 'Analytics' and 'JavaScript libraries'. It doesn't show any frameworks(Django) and programming languages(python). So, I went to wappalyzer and I looked up my website, but it didn't find any thing about my website. -
Custom ORM in Django. Based on Entity ID & Entity Type
My aim is to retrieve data from different model with the reference of entity type & entity id. Example: I have Customer model & Address model from django.db import models class Customer(models.Model): name = models.CharField(null=False, blank=False, max_length=255) email = models.EmailField(null=False, blank=False, unique=True) class Address(models.Model): entity_type = models.CharField(null=False, max_length=255) entity_id = models.PositiveIntegerField(null=False) address1 = models.CharField(max_length=255) address2 = models.CharField(max_length=255) for now i using raw query cursor.execute("SELECT * FROM customers AS cust INNER JOIN addresses AS addrs ON (cust.id = addrs.entity_id AND 'customer' = addrs.entity_type) WHERE cust.id IN (%s)", [ids]) But this is not Good solution. Take too much time when ids is in thousands of range. If is there any other way to archive those data. Then please give your solution in comments.. -
How to store password as Plaintext in Django
how to store password like "123abc" or "xyz123" -
Python Online Audio Streaming
I need to create a web application to steam live audio. Exactly something like that : a private radio podcast. This is my scenaio : A streamer is talking to microphone , there is a link to his/her live talking; and if you know the link , username and password you can listen this talking live. I will use Django. How can I open talker's microphone using python, and serving this to my users ? I know question is so unclear, but my problem is that complexity also. I know Django stuff but how I will listen "Talker's" microphone and how can I stream this talking . I am really struggling about streaming side. The question is about only "where to start, and how to stream live media?". Thanks. -
How to use django with sql server database from other server?
I'm planing to built an app using Django with SQL Server. But I'm going to develop the app in my computer but the database is already exist in other computer/server. How can I connect to that database in the other server and connect the Django which is in my computer? They are separate computers. -
How to make sceduled task properly in django using django-celery?
I new to django and recently i add django-celery 3.3.1 to my project. I want to add some scheduled task using celery from django admin but i cannot enabling worker It Return me an error : Exception Type: SyntaxError Exception Value: invalid syntax (redis.py, line 815) My django version : 3.0.3 python version : 3.7.1 How to make make it work properly? -
How to add custom title for form fields in Django?
I created this simple form: class FormsProject(forms.Form): fullname = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'placeholder': 'Basir Payenda'})) Django = forms.BooleanField(widget=forms.CheckboxInput()) Flask = forms.BooleanField(widget=forms.CheckboxInput()) gender = forms.ChoiceField( widget=forms.RadioSelect(), choices=SELECT_GENDER) comments = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control mb-2', 'rows': 4, }), help_text='Write here your message!') and it looks like How do I add a title asking something like "Your favorite frameworks: " before those checkbox, let me illustrate it: Help me add that title before checkbox, thanks -
django, check if object is part of queryset not returning proper value
for some reason I keep getting 'False' output and iim not sure why.. this is my queryset and condition in my view def book(request): test = books.objects.all().values('user') print(test) print(request.user.id) if request.user.id in test: exist = True else: exist = False print(exist) this is the console output, im expecting True, but im not sure why it isn't searching through it correctly. is it cause it's a list of tuples? <QuerySet [{'user': 1}, {'user': 1}, {'user': 1}, {'user': 1}, {'user': 1}, {'user': 3}]> currently logged in user id: 1 False -
Django framework view doesn't show my many to one types using nested serializers
Hi I'm trying to make an Rest API with django rest framework but following the docs to nested serializers after making a post request putting the custom classes values the get request show me that it's empty when I did the post correctly. There is my models class: from django.db import models # Create your models here. class Pista(models.Model): color = models.CharField(max_length=10) km_pista = models.FloatField(default=0) def __str__(self): return '{}'.format(self.color) class Forfait(models.Model): precio = models.FloatField(default=0) edad = models.IntegerField(default=0) def __str__(self): return '{}'.format("Precio " + str(self.precio) + ' edad ' + str(self.edad)) class Estacion(models.Model): nombre = models.CharField(max_length=30) ciudad = models.CharField(max_length=15) pais = models.CharField(max_length=20) descripcion = models.CharField(max_length=300) pistas = models.ForeignKey(Pista, on_delete=models.CASCADE, null=True) forfaits = models.ForeignKey(Forfait, on_delete=models.CASCADE, null=True) km_esquiables = models.FloatField(default=0) def __str__(self): return '{}'.format(self.nombre) My serializers: class PistaSerializer(serializers.ModelSerializer): class Meta: model = Pista fields = ('color', 'km_pista') class ForfaitSerializer(serializers.ModelSerializer): class Meta: model = Forfait fields = ('precio', 'edad') class EstacionSerializer(serializers.ModelSerializer): pistas = PistaSerializer(read_only=True, many=True) forfaits = ForfaitSerializer class Meta: model = Estacion fields = ('nombre', 'ciudad', 'pais', 'descripcion', 'pistas', 'forfaits', 'km_esquiables') depth = 1 My Views: class EstacionViewSet(viewsets.ModelViewSet): queryset = Estacion.objects.all() serializer_class = EstacionSerializer and urls: router = routers.DefaultRouter() router.register(r'estaciones', views.EstacionViewSet) urlpatterns = [ path('', include(router.urls)), ] I think many to many is … -
Secrets in a Django app on Google AppEngine (GAE)
I'm trying to develop a Django app on GAE, and using CloudBuild for CI/CD. I'm wondering what's the best way to pass secrets to my app (DB credentials, etc). I was able to follow instructions at https://cloud.google.com/cloud-build/docs/securing-builds/use-encrypted-secrets-credentials to read the secret from in my build step, and pass it in to my app as an environment variable. It's a bit hacky, but it works: - name: gcr.io/cloud-builders/gcloud entrypoint: 'bash' args: - '-c' - | TEST_PW=$(gcloud secrets versions access latest --secret=test-key) echo "TEST_PASSWORD=$${TEST_PW}" >> env_vars unset TEST_PW However, I'm not sure if this practice is safe. I dumped the env variables in running in my app (using print(dict(os.environ)) and the only sensitive values there are the secrets I passed in (all other GAE app related values are non-sensitive data). So questions: 1) Is storing secrets in env variables safe in an app in AppEngine, i.e. can they be stolen by "somehow" dumping them through print(dict(os.environ))? 2) Or is the better option to fetch them from Secret Manager in Django (for e.g. in settings.py)? (I'm worried about restarts or version switches here, and if they'll affect this option) 3) Or is there an even better option? Thanks. -
models.OneToOneField(User, on_delete=models.CASCADE) is not working. User table is updating but not the UserModelInfo Table
I am able to store an user in the User table however the UserModelInfo table is not getting updated. project github link - https://github.com/souradip-code/Django_myproject_1 So what I basically want is an OneToOne relationship with django built-in User class with UserInfo Class and if I add one user, both tables should update and every user from the UserInfo table should point to an user in the User table. Here is what I've done so far - Models.py JOB_CHOICES = ( (1, "Designer"), (2, "Manager"), (3, "Accounting") ) CONTACT_CHOICES = ( (1, "+91"), (2, "+92"), (3, "+93"), ) class UserInfoModel(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) fullname = models.CharField(max_length=264,unique=True) email = models.EmailField(max_length=255) contact_pref = models.IntegerField(choices=CONTACT_CHOICES, default=1) contact_suff =models.IntegerField() job= models.IntegerField(choices=JOB_CHOICES, default=1) pwd1 = models.CharField(max_length=20) pwd2 = models.CharField(max_length=20) def __str__(self): return user.fullname enter code here Forms.py JOB_CHOICES = ( (1, "Designer"), (2, "Manager"), (3, "Accounting") ) CONTACT_CHOICES = ( (1, "+91"), (2, "+92"), (3, "+93"), ) class RegisterForm(forms.ModelForm): fullname = forms.CharField(max_length=264,widget=forms.TextInput(attrs={'class':'form-control'})) email = forms.EmailField(max_length=255,widget=forms.EmailInput(attrs={'class':'form-control'})) contact_pref = forms.ChoiceField(choices=CONTACT_CHOICES,widget=forms.Select(attrs={'class':'custom-select'})) contact_suff =forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control'})) job= forms.ChoiceField(choices=JOB_CHOICES,widget=forms.Select(attrs={'class':'custom-select'})) pwd1 = forms.CharField(max_length=20,widget=forms.PasswordInput(attrs={'class':'form-control'})) pwd2 = forms.CharField(max_length=20,widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = UserInfoModel # fields = "__all__" exclude =("user",) Here please check the Meta class configuration Views.py def user_register(request): template = 'basic_app/register.html' if request.method == 'POST': form … -
return primary key from CreateAPIView after creating an object
Django 3. I am posting data to a CreateAPIView in django. I can POST the object to the database no problem. What I want to do is return the primary key from the created object to my frontend (Angular 8). I am using that primary key in my redirect url to load the next page. -
Why Django Query for Two DateTimeFields Equality Does Not Work?
I have a model: class Host(models.Model): create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) I would like to filter out all objects that have create_date.date() == update_date.date(), so I use this Django Query: Host.objects.filter(create_date__date=F("update_date__date")).count() Assuming, my database does have hosts that have create_date.date() == update_date.date(), so I expect the return value for count() > 0; however, I get 0 as the result. Meanwhile, if I use this query: Host.objects.filter(create_date__date__lt=F("update_date__date")).count() I will get my expected result. Question: Why cannot I do equality comparison for Django query on DateTimeField? -
Apache/2.4.29 (Ubuntu) Server at domain Port 443
I have a VM Instances server installed with Apache2, mod_wsgi and Django. The server has both python 2.7 and 3.4 installed which comes with the server os Ubuntu. Error log : tail -f /var/log/apache2/error.log [Thu Apr 23 03:19:57.493146 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] Traceback (most recent call last): [Thu Apr 23 03:19:57.493207 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] File "/var/www/WFH_project/wfhProject/wfhProject/wsgi.py", line 16, in <module> [Thu Apr 23 03:19:57.493269 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] application = get_wsgi_application() [Thu Apr 23 03:19:57.493363 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] File "/var/www/WFH_project/myDjangoEnv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Thu Apr 23 03:19:57.493369 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] django.setup(set_prefix=False) [Thu Apr 23 03:19:57.493375 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] File "/var/www/WFH_project/myDjangoEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [Thu Apr 23 03:19:57.493379 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] apps.populate(settings.INSTALLED_APPS) [Thu Apr 23 03:19:57.493385 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] File "/var/www/WFH_project/myDjangoEnv/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate [Thu Apr 23 03:19:57.493389 2020] [wsgi:error] [pid 4289:tid 140381721962240] [remote 122.228.19.79:35227] raise RuntimeError("populate() isn't reentrant")