Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing parameters to login_redirect_url
I'd like my login page to redirect a user to an instance of a page. Such an instance will be denoted as follows: www.example.com/adminpage/username This is what I have in my settings.py LOGIN_REDIRECT_URL = 'leicunnadmin' LOGOUT_REDIRECT_URL = 'login' In the urls.py: urlpatterns = [ path('', views.index, name='index'), path('leicunnadmin/<str:user>', views.leicunnAdmin, name='leicunnadmin'), ] The following is the code from the views.py script. My aim here was to check that the user is authenticated, get their username and append that to the URL. (The code) @login_required def leicunnAdmin(request, user): username = None User = get_user_model() if request.user.is_authenticated: username = request.user.username get_logged_user = User.objects.get(username=user) print('get_logged_user: '+username) return render(request, 'leicunnadmin.html') else: return render(request, 'login') Instead what I get when I log in is www.example.com/adminpage. When I type in the logged in username (www.example.com/adminpage/manuallytypedusername), it then redirects to the right page. Is there no way to automate this? -
How to execute a specific code in a defined period -Django-
I would like to know how to automatically execute a code in Django within a defined period of time. I'm building a web crawler that collects information and stores it in a JSON file and a function that reads the file and stores the file information in a SQLite database. This information is rendered and visible on my website. At the moment I have to run the crawler and the function that saves the data in a database with a click on a button, but that is very ineffective. It would be better if the database information were updated automatically, about every 6 hours (of course, only if the server is running). -
how CKEDITOR save images and is that an efficient way to use that for building blog and posts with several images?
i want to build a blog app in django and create Posts including multiple images. i don't want to create custom cms and want to use django admin cms. but i have to use CKEDITOR to do that. because i want to include images between content textarea section. i wanna to know how CKEDITOR saves images and files. does it save images into database? is this an efficient way to biuld blog? thanks for helps. from django.conf import settings from django.db import models from django.contrib.auth.models import User name = models.CharField(max_length=32) class Meta: verbose_name_plural = "Categories" def __unicode__(self): return self.name class Category(models.Model): name = models.CharField(max_length=32) class Meta: verbose_name_plural = "Categories" def __unicode__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=32) def __unicode__(self): return self.name class Post(models.Model): author = models.ForeignKey(User) category = models.ForeignKey(Category) title = models.CharField(max_length=64,unique=True) symbol = models.CharField(max_length=2) tags = models.ManyToManyField(Tag) byline = models.CharField(max_length=255) background_image = models.URLField(verify_exists=True) slug = models.SlugField(max_length=128) content = models.TextField() updated_on = models.DateField(auto_now=True) created_on = models.DateField(auto_now_add=True) publish_on = models.DateField() list_display = ('title', 'category', 'tags', 'author', 'publish_on','created_on','updated_on') search_fields = ['title','byline','symbol'] list_filter = ['publish_on','created_on'] date_hierarchy = 'pub_date' ` -
Django UpdateView for Profile model that also includes a User form
Using Django 2.x, I have a Profile model, and I want to update some User fields in the Profile's UpdateView, for example, User.email I can get the email field to display, and to show the current value, but I can't figure out how to get it to update. Here's my setup: models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # other fields forms.py: class UserForm(forms.ModelForm): class Meta: model=User fields=('email') class ProfileForm(forms.ModelForm): class Meta: model=Profile fields=(...) views.py class ProfileUpdate(UpdateView): model=Profile form_class = ProfileForm user_form_class = UserForm def get_context_data(self, **kwargs): ... user = get_object_or_404(Profile, pk=self.kwargs.get('pk')).user context['user_form']= self.user_form_class(instance=user) Everything up to here seems to work. The user form works and the current email address appears in the form. However, this is where I get stuck, I don't know how to save that email address. Still within the ProfileUpdate, this is what I'm trying: def post(self, request, *args, **kwargs): user_form = self.user_form_class(request.POST) if user_form.is_valid(): user_form.save() # code makes it this far when submitting form. return super(ProfileUpdate, self).post(self, request, *args, **kwargs) Although the code is run, only the Profile model is updated, the User model doesn't get an updated email address. -
Blank page when using Vue in Django
I recently added VueJS to my Django project, following this guide. I'm now trying to test Vue, to see if it's running, by running this template: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title>Django Vue Integration</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons"> </head> <body> <noscript> <strong>We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"> <app></app> </div> {% render_bundle 'app' %} <!-- built files will be auto injected --> </body> </html> It should just render the default VueJS page. The problem is that when i run Django using manage.py runserver, i will only see a blank page on http://127.0.0.1:8000/. I'm not receveing any error in my cmd console, but in my dev tools i found this error: GET http://127.0.0.1:8000/app.js net::ERR_ABORTED 404 (Not Found) <script type="text/javascript" src="http://127.0.0.1:8000/app.js" ></script> Any advice on how to fix this issue? Thanks in advance -
Allow user to make a table
I'm making a simple Time Attendance App in Django. I had this idea in mind to allow the Admins to make their own custom salary structures. I just don't know how that works Let's say I have the following: - A users table with all the user's information. - An attendance table with his clock in and clock out times - And a payroll structure table with the payroll structure for that employee. I want to enable the admin (Me) to first click on the top, goto create a new Payroll Structure. Here, I would choose the days my employee would work, his pay, his special days, his overtime etc. I understand that I can do this in a the same employee table as well but I want to take away the hassle of doing it again every-time I create a new employee. So this way, I create a structure, then when creating an employee, I just choose which structure I want to use for that employee. How would I do this? The first thing I think I should do is create the models but how I do make the models flexible? class CPayrollStructures(models.Model): class CPayrollStructureOne(): This is something that … -
Why is my Django Rest Framework Search filter not working?
Here is my code. I get no errors, and I can see the search button that was added to the browsable API. The problem though is the search does not work. No matter what I type into the search, it just returns every objects. from rest_framework import status, filters class JobView(GenericAPIView): serializer_class = JobSerializer filter_backends = [filters.SearchFilter] search_fields = ['name'] def get_queryset(self): return Job.manager.all() def get(self, request, format=None): queryset = self.get_queryset() if queryset.exists(): serializer = JobSerializer(queryset, many=True) return Response(serializer.data) else: return Response({"Returned empty queryset"}, status=status.HTTP_404_NOT_FOUND) endpoint http://localhost:8000/jobs/?search=something returns the same as http://localhost:8000/jobs/ No matter what I put in the search string, it returns jobs. -
In a model can ForeignKey fields be used to dynamically populate the choices of a CharField in the same model?
Let's say I'm making a Django app to track different landscape companies and which employees carry out specific services. And let's say these are my models: class Employees(models.Model): employee_name = models.CharField(max_length=255, ) def __str__(self): return self.employee_name class LandscapeCompanies(models.Model): company_name = models.CharField(max_length=255) company_url = models.URLField() employees = models.ForeignKey(Employees, on_delete=models.SET_NULL, null=True, blank=True) mow_the_lawn = models.CharField(choices=[], max_length=255, null=True, blank=True) weed_the_garden = models.CharField(choices=[], max_length=255, null=True, blank=True) sweep_the_driveway = models.CharField(choices=[], max_length=255, null=True, blank=True) def __str__(self): return company_name For Landscape Company "A" is there a way to have the choices=[] for the services be populated with the ForeignKey employees already associated with Landscape Company "A"? Or rephrased, In the LandscapeCompanies model in Django Admin I'd like to the value of each of the services to be a choice of the employees that are already ForeignKeys for this particular Landscape Company. Note: having to save LandscapeCompanies before the services can be filled out is acceptable -
Django as ORM - Perform update query asynchronously without blocking
I'm using Djang as my ORM. As part of my code I want to initiate an update request some_object = SomeObject.objects.get(...) calculated_value = func(some_object.value1, some_object.value2) some_object.value1 = calulated_value # This line should happen asynchrnoously and I don't if it fails some_object.save() # Can be replaced with some_object.update(value=calculated_value) # continue doing other stuff The line some_object.save() has some latency, but actually, I don't really mind if it fails, and I don't need its result. I want it to be handled by Django without the rest of the code waiting for it -
Issue with requests in django rest framework
I created an API using django restframework. It works well on the django development server. When the application is migrated to a web server (apache mod wsgi, nginx - gunicorn) it works fine only if the pagination is set to 100 records per page, if the pagination is set to more than 100 records, requests between 100 and 200 records They remain stalled or blocked. I deployed the application in Apache with wsgi and gunicorn with nginx. But the problem persists. It works perfect on the django development server with any page size and works well on the server if I set the page size to 100 records. View class SoftwareList(generics.ListCreateAPIView): queryset = SoftwareModel.objects.all().order_by('-id') serializer_class = SoftwareSerializer http_method_names = ['get'] filter_backends = (DjangoFilterBackend,) filter_fields = ('product_type',) Settings REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } Expected: The request with a pagination different than 100. Actual: Request Stalled/Blocking -
I want to create a comment form of user (Create Edit and Delete comment button) with DetailView and FormMixin
I want to create a comment form of user (Create, Edit and Delete Comment) with DetailView and FormMixin. My user can created comment. But when i create button to edit or delete comment. I don't know what should i do now. class Comment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='comments', null=True) user_commented = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) reply = models.ForeignKey('Comment', on_delete=models.CASCADE, null=True, related_name="replies") comment = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return '{} {}'.format(self.book.title, self.user_commented) This is my ModelForm class CommentForm(ModelForm): comment = forms.CharField(label="", widget=forms.Textarea(attrs={'title': 'Comment', 'class': 'form-control', 'placeholder': 'Text Input Here !!!', 'style': 'margin-left: 40px', 'rows': 4, 'cols': 100})) class Meta: model = Comment fields = ('comment',) exclude = ('user_commented', 'book') def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.book = kwargs.pop('book') super(CommentForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('comment', css_class='form-group col-12 m-auto',), css_class='form-group' ), FormActions( Submit('save', 'Submit', css_class='btn-success'), ), ) I don't know how to create update or delete with form in view logic. class BookDetailView(FormMixin, generic.DetailView): model = Book template_name = 'catalog/book_detail.html' query_pk_and_slug = True form_class = CommentForm def get_form_kwargs(self, *args, **kwargs): kwargs = super(BookDetailView, self).get_form_kwargs(*args, **kwargs) kwargs['user'] = self.request.user.username kwargs['book'] = Book.objects.get(slug=self.kwargs.get(self.slug_url_kwarg)) return kwargs def get_success_url(self): return reverse('catalog:book-detail', … -
adding formset fields dynamically in django with javascript
I created a js function which increments ID's of formset fields. The idea is to add and remove fields dynamically. However when I delete a field dynamically and click submit the form doesn't submit.The error the form displays is that the field I deleted is required. Where do I need to make some changes to be able to remove fields dynamically and don't get an error that the field i deleted is required for submittion? This is how my django template looks like: <ul class="clone--list"> {% for skill_form in skill_formset %} {% for hidden in skill_form.hidden_fields %} {{ hidden }} {% endfor %} <li> {{ skill_formset.management_form }} {{ skill_form.errors }} {{ skill_form.skill_name }} <a class="clone--add" id="add_skill">>Add Skill</a> <a class="clone--remove">Remove</a> </li> {% endfor %} </ul> javascript: $(".clone--list").on("click", ".clone--add", function () { var parent = $(this).parent("li"); var copy = parent.clone(); parent.after(copy); copy.find("input[type='text'], textarea, select").val(""); copy.find("*:first-child").focus(); updateskill(); }); $(".clone--list").on("click", "li:not(:only-child) .clone--remove", function () { var parent = $(this).parent("li"); parent.remove(); updateskill(); }); function updateskill() { var listskill = $("ul.clone--list li"); listskill.each(function (i) { var skill_TOTAL_FORMS = $(this).find('#id_form-TOTAL_FORMS'); skill_TOTAL_FORMS.val(listskill.length); var skill_name = $(this).find("input[id*='-skill_name']"); skill_name.attr("name", "form" + i + "-skill_name"); skill_name.attr("id", "id_form-" + i + "-skill_name"); }); } view: def profile_edit(request): skill_instance = ProfileSkill.objects.filter(profile__user_id=request.user.id) if request.method … -
YouTube request works fine on dev server, but is declined when sent from VM prod server
The following code (from views.py) is used to download YouTube mp3 from video with pytube library, and is working fine on development server: import os from django.shortcuts import render from django.http import HttpResponse from django.conf import settings from pytube import YouTube # Create your views here. def index(request): url = 'https://www.youtube.com/watch?v=v2JsxXxf1MM' audio = get_audio(url) download(audio) return HttpResponse('Downloaded!!!') def get_audio(url): yt =YouTube(url) all_streams = yt.streams.all() audio_mp4_stream_itag= [stream.itag \ for stream in all_streams \ if stream.mime_type == 'audio/mp4'][0] audio = yt.streams.get_by_itag(audio_mp4_stream_itag) return audio def download(audio): dst = os.path.join(settings.BASE_DIR, 'tester', 'audio') audio.download(dst, 'downloaded_audio') However, when I run the project on my Digital Ocean droplet (Ubuntu VM), YouTube blocks the request. The error is: Traceback (most recent call last): File "/root/testenv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/root/testenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/root/testenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/requests_test/requests_test/tester/views.py", line 14, in index audio = get_audio(url) File "/root/requests_test/requests_test/tester/views.py", line 22, in get_audio yt =YouTube(url, on_progress_callback=log) File "/root/testenv/lib/python3.5/site-packages/pytube/main.py", line 88, in init self.prefetch_init() File "/root/testenv/lib/python3.5/site-packages/pytube/main.py", line 96, in prefetch_init self.prefetch() File "/root/testenv/lib/python3.5/site-packages/pytube/main.py", line 160, in prefetch self.watch_html = request.get(url=self.watch_url) File "/root/testenv/lib/python3.5/site-packages/pytube/request.py", line 21, in get response = urlopen(url) File "/usr/lib/python3.5/urllib/request.py", line 163, in … -
Django validator not preventing invalid IPv4 address from being added to database
I am experimenting with Django's validate_ipv46_address validator in my model: class Policy(models.Model): ... omitted for brevity ... allowed_network_ips = ArrayField(models.CharField(max_length=225, null=True, validators=[validate_ipv4_address])) ... I have a view with a POST method that creates a Policy object which looks like: class PolicyView(generics.GenericAPIView): ... def post(self, request, namespace_id): ... allowed_network_ips = request.data.get('allowed_network_ips') ... try: np = Policy.objects.create( ... allowed_network_ips=allowed_network_ips, ... ) serialized_np = PolicySerializer(np, many=False) except Exception as ex: ... return Response({"message": message}, status=status.HTTP_400_BAD_REQUEST) return Response(serialized_np.data, status=status.HTTP_200_OK) I am testing this with this curl script that has an invalid ipv4 address. The curl script looks like this: curl -v -X POST \ "http://example.com/namespace/49/policy" \ ... -d '{ "..., "allowed_network_ips": ["not.an.ipv4.addres"], ... }' I was hoping I would get some sort of error because I do not think not.an.ipv4.addres is a valid ipv4 address (I could be wrong there), but the POST works and a Policy with allowed_network_ips of not.an.ipv4.addres gets created. What am I doing wrong here? -
Annotation field is str instead of datetime.datetime
Example I'm trying to annotate objects using data from a related model's DateTimeField. class Author(models.Model): name = models.CharField(max_length=256) class Book(models.Model): name = models.CharField(max_length=256) is_published = models.BooleanField() publication_date = models.DateTimeField() author = models.ForeignKey(Author, on_delete=models.PROTECT) queryset = Author.objects.annotate( has_unpublished=Exists( Book.objects.filter( author=OuterRef('pk'), is_published=False)) ).annotate( last_published_date=Max( 'book__publication_date', filter=Q(book__is_published=True) ) ) I alternate between the default local sqlite3 database and MySQL (with mysqlclient). SQLite works and MySQL crashes. Here's the reason: compilers for both databases results = compiler.execute_sql(**kwargs) return a list of lists of tuples of int and string, like so: SQLite <class 'list'>: [[(1, 'Alice', 1, '2017-01-01 01:00:00'), (2, 'Bob', 0, '2019-01-05 13:00:00'), (3, 'Carol', 1, None), (4, 'Dan', 0, None)]] MySQL <class 'list'>: [((1, 'Alice', 1, '2017-01-01 01:00:00.000000'), (2, 'Bob', 0, '2019-01-05 13:00:00.000000'), (3, 'Carol', 1, None), (4, 'Dan', 0, None))] Now, when the SQLite backend sees a supposed datetime field, it generates a converter at runtime using this method: django.db.backends.sqlite3.operations.DatabaseOperations def convert_datetimefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.datetime): value = parse_datetime(value) if settings.USE_TZ and not timezone.is_aware(value): value = timezone.make_aware(value, self.connection.timezone) return value which works ok. The MySQL backend, however, does this: django.db.backends.mysql.operations.DatabaseOperations def convert_datetimefield_value(self, value, expression, connection): if value is not None: value = timezone.make_aware(value, self.connection.timezone) … -
Informix db conection driver for django?
can some1 help me with any example to connect django 5.8 with external informix db, i am try some driver but I don't get positive results -
Call a Django Rest Framework view within another Django Restframework view
I've searched stack overflow and the internet for a solution to call a django restframework ListAPIView from anotehr django restframework APIView. I've tried: class ViewA(APIView): def get(request): response = ViewB.as_view({'get':'list'})(request) print response.render() # do other things with the response However, I get the error: response = SubsidiariesStatisticsView.as_view({'get': 'list'})(request) TypeError: as_view() takes exactly 1 argument (2 given) How do I pass in a request from viewA to viewB and get a response? Also, class ViewB has a get_serializer_context method. How do I call that from ViewA? -
Django form creates default User rather than acustom User. How do I create a Custom User?
Trying to extend Django's basic user model to a custom user model. I have a form for users to register, but when the form is sent it creates a default user, not a custom user. I want it to create a custom user. The only way I seem to be able to create a custom user currently is through admin. Here is my Django custom user model, which exists and can add users via admin. class MyUserManager(BaseUserManager): def create_user(first_name, last_name, zipcode, email, username, password): if not first_name: raise ValueError("Users must have a first name.") if not last_name: raise ValueError("Users must have a last name.") if not zipcode: raise ValueError("Users must have a zipcode.") if not email: raise ValueError("Users must have an email.") if not username: raise ValueError("Users must have a username.") if not password: raise ValueError("Users mush have a password.") user=self.model( first_name = first_name, last_name = last_name, zipcode = zipcode, email=email, is_logged_in=is_logged_in, is_bot=is_bot ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=25, validators … -
Django urls slug must contain word
here is my URL: /jobs-in-new-york here is my urls.py url(r'^account/', include('.account.urls')), url(r'^account/', include('allauth.urls')), url(r'^payment/', include('.payments.urls', namespace='payments')), url(r'^student/', include('.student.urls')), url(r'^employer/', include('.employer.urls')), url(r'^(?P<slug>[-\w\/]+)', JobSearchView.as_view(), name='job_search') How can I change this regex ^(?P<slug>[-\w\/]+) so that if slug contains word jobs, it gets matched! -
How to get data from google classroom api?
I need to get classroom info and course posts from google-classroom. Thus I have used oauth to authorize user first. And then access data using the googles quickstart.py example def authorized(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=SCOPES) flow.redirect_uri = 'http://localhost:8000/google-class/oauth2callback/' flow.code_verifier = rs authorization_url, state = flow.authorization_url( access_type='offline', prompt='consent', include_granted_scopes='true') request.session['state'] = state some = state print("/n" + "The state is =" + state + "/n") return redirect(authorization_url) def oauth2callback(request): state = request.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=SCOPES, state=state) flow.redirect_uri = 'http://localhost:8000/google-class/oauth2callback/' flow.code_verifier = rs authorization_response = request.get_full_path() # print(request.get_full_path()) flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials # request.session['credentials'] = credentials_to_dict(credentials) cred = credentials_to_dict(credentials) if 'credentials' in request.session: # Load credentials from the session. credentials = google.oauth2.credentials.Credentials( cred["token"], refresh_token = cred["refresh_token"], token_uri = cred["token_uri"], client_id = cred["client_id"], client_secret = cred["client_secret"], scopes = cred["scopes"]) service = googleapiclient.discovery.build(API_SERVICE_NAME,API_VERSION, credentials=credentials) # Call the Classroom API results = service.courses().list(pageSize=1).execute() print('somethign ') print("blaad,lasd," + results) courses = results.get('courses', []) if not courses: print('No courses found.') else: print('Courses:') for course in courses: print(course['name']) return render(request,'api/google-class.html') But when the oauth2callback() is called it goes straight to the return statement instead of printing. And the terminal gives - "GET /google-class/oauth2callback/?state=KG8awXXNDQehgDEKcRbltVBxrv4Lxv&code=4/nQHoFfykiDmkS_CPg_zGvCJxJyob52r7TLcUsDTrEJRck0nLZki7Ukf9aiug6kqR0NMs6KrKQiCMKCIod-e1Iao&scope=https://www.googleapis.com/auth/classroom.courses.readonly HTTP/1.1" 200 5273 so how can I get the classroom names here? -
Why is coverage.py looking for a file titled 'blub'?
I'm working on a django project and recently installed coverage.py to generate coverage reports for our unit and integration tests. When I generate the report, it gives the following error message: " blub NoSource: No source for code 'home/me/Documents/myProject/blub'. Aborting report output, consider using -i. " The report then prints out and looks mostly normal. However, if I subsequently try to generate the report as html, the same error is printed and the index.html file is not generated. Does anyone know why coverage is looking for 'blub' or how I can disable it? I have tried specifying source, as described in django documents as follows: coverage run --source='.' manage.py test coverage report coverage html -
Django does not find static files for serving
I am trying to serve some static files. This is my project structure: Django Project Structure I am trying to serve all static files in the "(...)/templates/architectui/assets". For that I updated this line in the settings.py for the django project: STATIC_URL = 'templates/architectui/assets/' And this is how my urls.py in the "dashboard" app looks like: from django.urls import path from dashboard import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("", views.index, name="index"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Unfortunately if I try to open one of the files within the "assets" dir like for example "http://127.0.0.1:8000/dashboard/images/avatars/1.jpg" the following error occurs: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/images/avatars/1.jpg Using the URLconf defined in frontend.urls, Django tried these URL patterns, in this order: admin/ dashboard/ [name='index'] dashboard/ ^templates/architectui/assets/(?P<path>.*)$ The current path, dashboard/images/avatars/1.jpg, didn't match any of these. Has anyone an idea on how to fix this issue? -
Wheel for mysqlclient
I tried to dowload mysqlclient and it give me this error Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\acer\appdata\local\programs\python\python37- 32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Acer\\Ap pData\\Local\\Temp\\pip-install-4p7ik_w4\\mysqlclient\\setup.py'"'"'; __file__=' "'"'C:\\Users\\Acer\\AppData\\Local\\Temp\\pip-install- 4p7ik_w4\\mysqlclient\\se tup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open) (__file__);code=f.read().re place('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"' exec'"'"'))' bdist_wheel -d 'C:\Users\Acer\AppData\Local\Temp\pip-wheel- l3n80_sf ' --python-tag cp37 cwd: C:\Users\Acer\AppData\Local\Temp\pip-install-4p7ik_w4\mysqlclient\ Complete output (30 lines): I installed wheel for mysqclient and it give me C:\Users\Acer>pip3 install C:\Users\Acer\Desktop\mysite\mysqlclient-1.4.2- cp35-c p35m-win32.whl ERROR: mysqlclient-1.4.2-cp35-cp35m-win32.whl is not a supported wheel on this platform. I'm using windows 7 32bit python 3.7.4 and wondering if there is any wheel for windows 7 32 bit or if I can install mysqlclient without wheel I alerady installed c++ builds tools and django and when I tried to upgrade wheel it tell me that all requirement exist and there is no update for wheels or env -
Xamarin.Forms with Django REST API
I am working on a Xamarin.Forms application and want to have both a website and an app for my application. If I have built a website with Django Web Framework and use a REST API to POST/GET information to and from the server, is that good practice? Are there many downsides associated with Python web framework sending JSON data via a REST API. Thank you for your help! -
How to automate django deployment?
OK, I am desperate enough to finally post a github question. SUMMARY: Django deploy -> digital ocean droplet -> nginx and gunicord + git pull It works, but manually writing all the commands is way to tedious + error prone. I have been trying to find a suitable tool ever since, and kinda need some advice. SOO FAR: I have tried Fabric, BUUUT complexity and simplicity baffles me. Some tutorial are way to trivial, some are way too complex and 95 % of them seems to be outdated(this seems relevant in this case , because syntax has changed drastically) In addition, the most basic example in docs don't work no matter how many times I have tried to correct it(ssh connection vie password). P.S. I am completely new to devops, so a lot of things is confusing for me Beside that, I have tried to dive into some other tools like bash scripting and ansible and dropped them shortly after, mainly due to them not being as alluring as Fabric seems to be. My question is! Should I continue tring to solve Fabric, or is there some other commonly used way to make deployment a simple and enjoyable matter while …